i'm learning MongoDB and i have the next questions.
There are my MongoDB documents
This is coordenada document
> db.coordenada.find().pretty()
{
"_id" : ObjectId("5579b81342a31549b67ad00c"),
"longitud" : "21.878382",
"latitud" : "-102.277364"
}
{
"_id" : ObjectId("5579b85542a31549b67ad00d"),
"longitud" : "21.878626",
"latitud" : "-102.280379"
}
{
"_id" : ObjectId("5579b89442a31549b67ad00e"),
"longitud" : "21.878845",
"latitud" : "-102.283512"
}
{
"_id" : ObjectId("5579b8bf42a31549b67ad00f"),
"longitud" : "21.879253",
"latitud" : "-102.286698"
}
{
"_id" : ObjectId("5579b8dd42a31549b67ad010"),
"longitud" : "21.879203",
"latitud" : "-102.291558"
}
{
"_id" : ObjectId("5579b8fd42a31549b67ad011"),
"longitud" : "21.878427",
"latitud" : "-102.296375"
}
{
"_id" : ObjectId("5579b91d42a31549b67ad012"),
"longitud" : "21.877571",
"latitud" : "-102.299659"
}
And this is rutas document
> db.rutas.find().pretty()
{
"_id" : "1",
"nombre" : "Ruta Penal",
"numero" : "20",
"coordenadas" : [
DBRef("coordenada", "5579b91d42a31549b67ad012")
]
}
{
"_id" : "2",
"nombre" : "Ruta Penal",
"numero" : "20",
"coordenadas" : [
DBRef("coordenada", "5579b91d42a31549b67ad012")
]
}
{
"_id" : "3",
"nombre" : "Ruta Penal",
"numero" : "20",
"coordenadas" : [
DBRef("coordenada", "5579b85542a31549b67ad00d")
]
}
{
"_id" : 6,
"nombre" : "Ruta Penal",
"numero" : "20",
"coordenadas" : [
DBRef("coordenada", "5579b85542a31549b67ad00d")
]
}
>
What i'm tryin to do, it's obtain the "longitud" and "latitud" from "coordenada" but only for the "numero" 20 of "rutas" document for instance
How can i do this?
PS sorry for the spanish terms.
According to the mongodb site for DBRef, you need to use drivers to unpack reference. I don't think mongo shell can unpack it for you.
http://docs.mongodb.org/manual/reference/database-references/
To resolve DBRefs, your application must perform additional queries to return the referenced documents. Many drivers have helper methods that form the query for the DBRef automatically. The drivers [1] do not automatically resolve DBRefs into documents.
DBRefs provide a common format and type to represent relationships among documents. The DBRef format also provides common semantics for representing links between documents if your database must interact with multiple frameworks and tools.
Unless you have a compelling reason to use DBRefs, use manual references instead.
Based on that, I would suggest to change it using manual reference (just the document id) instead.
To answer your question however, you can use any language drivers but below is an example in Python using pymongo:
from pymongo import MongoClient
from bson.objectid import ObjectId
from bson.dbref import DBRef
client = MongoClient()
db = client.testDB
rutas_20 = list(db.rutas.find({"numero": "20"}))
for ruta in rutas_20:
for coordenada in ruta.get('coordenada'):
coord_doc = db.coordenada.find_one({"_id": ObjectId(coordenada.id) })
print coord_doc.get('longitud'), coord_doc.get('latitud')
You can also use db.dereference(DBRef()) as well.
Hope it helps.
Cheers.
Yes, you can definitely obtain the latitude and longitude of the particular item by referencing the object id of the other class.
To use momgo dbRef you have to use the specific drivers depending on the particular language you are using. The driver documentation will tell you about the functions you can use.
I use PHP and hence refer to,
http://www.php.net/manual/en/class.mongodbref.php/
Related
I have almost no experience in SQL or noSQL.
I need to update every document so that my fields "Log*" are under the new field "Log"
I found some help from this StackOverflow, but I am still wondering how to move the data.
Thank you very much
Original document
// collection: Services
{
"_id" : ObjectId("5ccb4f99f4953d4894acbe79"),
"Name" : "WebAPI",
"LogPath" : "Product\\APIService\\",
"LogTypeList" : [
{
"Name" : "ApiComCounter",
"FileName" : "ApiComCounter.log"
},
{
"Name" : "ApiService",
"FileName" : "ApiService.log"
}
]
}
Final Document
// collection: Services
{
"_id" : ObjectId("5ccb6fa2ae8f8a5d7037a5dd"),
"Name" : "InvoicingService",
"Log" : {
"LogPath" : "Product\\APIService\\",
"LogTypeList" : [
{
"Name" : "ApiComCounter",
"FileName" : "ApiComCounter.log"
},
{
"Name" : "ApiService",
"FileName" : "ApiService.log"
}
]
}
}
This requires MongoDB 4.2 or higher:
db.<collection>.updateMany({}, [
{$set: {"Log.LogPath": "$LogPath", "Log.LogTypeList": "$LogTypeList"}},
{$unset: ["LogPath", "LogTypeList"]}
])
When I use this method, I get all documents from _User collection. (as expected)
db.getCollection("_User").find({ "_id" : { $nin: [] }})
However, when I add at least one string to $nin array:
db.getCollection("_User").find({ "_id" : { $nin: ["7HpHbmF5iu","ga61t3afsa"] }})
I get empty results. (expected - to get all documents without the ones with ids 7HpHbmF5iu and ga61t3afsa)
MongoDB version 3.2.6
These are two documents I want to filter from all:
{ "_id" : "7HpHbmF5iu", "expiration_date" : ISODate("2015-12-28T08:51:21.252Z"), "_created_at" : ISODate("2015-10-29T08:51:23.302Z"), "_updated_at" : ISODate("2016-03-10T17:37:45.262Z"), "gender" : "female", "firstName" : "Toma", "verification" : "verified", "birthdayDate" : ISODate("1995-02-15T00:00:00Z") }
{ "_id" : "ga61t3afsa", "expiration_date" : ISODate("2015-12-27T07:54:21.235Z"), "_created_at" : ISODate("2015-10-28T07:11:22.102Z"), "_updated_at" : ISODate("2016-03-11T16:11:10.100Z"), "gender" : "female", "firstName" : "Goda", "verification" : "verified", "birthdayDate" : ISODate("1992-09-13T00:00:00Z") }
It was an error in Azure DocumentDB with Mongo, however I've chosen not to use their services, so I don't know if they've already fixed it.
I need get a specific object in array of array in MongoDB.
I need get only the task object = [_id = ObjectId("543429a2cb38b1d83c3ff2c2")].
My document (projects):
{
"_id" : ObjectId("543428c2cb38b1d83c3ff2bd"),
"name" : "new project",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b"),
"members" : [
ObjectId("5424ac37eb0ea85d4c921f8b")
],
"US" : [
{
"_id" : ObjectId("5434297fcb38b1d83c3ff2c0"),
"name" : "Test Story",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b"),
"tasks" : [
{
"_id" : ObjectId("54342987cb38b1d83c3ff2c1"),
"name" : "teste3",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
},
{
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
]
}
]
}
Result expected:
{
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
But i not getting it.
I still testing with no success:
db.projects.find({
"US.tasks._id" : ObjectId("543429a2cb38b1d83c3ff2c2")
}, { "US.tasks.$" : 1 })
I tryed with $elemMatch too, but return nothing.
db.projects.find({
"US" : {
"tasks" : {
$elemMatch : {
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2")
}
}
}
})
Can i get ONLY my result expected using find()? If not, what and how use?
Thanks!
You will need an aggregation for that:
db.projects.aggregate([{$unwind:"$US"},
{$unwind:"$US.tasks"},
{$match:{"US.tasks._id":ObjectId("543429a2cb38b1d83c3ff2c2")}},
{$project:{_id:0,"task":"$US.tasks"}}])
should return
{ task : {
"_id" : ObjectId("543429a2cb38b1d83c3ff2c2"),
"name" : "jklasdfa_XXX",
"author" : ObjectId("5424ac37eb0ea85d4c921f8b")
}
Explanation:
$unwind creates a new (virtual) document for each array element
$match is the query part of your find
$project is similar as to project part in find i.e. it specifies the fields you want to get in the results
You might want to add a second $match before the $unwind if you know the document you are searching (look at performance metrics).
Edit: added a second $unwind since US is an array.
Don't know what you are doing (so realy can't tell and just sugesting) but you might want to examine if your schema (and mongodb) is ideal for your task because the document looks just like denormalized relational data probably a relational database would be better for you.
I'm trying to use the MongoDB to reassign IDs. However, it is not setting IDs equal to the value I assign, but rather it is creating a new ObjectId. How do I assign my own ID?
> db.pGitHub.find();
{ "_id" : ObjectId("516f202da1faf201daa15635"),
"url" : { "raw" : "https://github.com/Quatlus",
"domain" : "github.com", "canonical" : "https://github.com/quatlus" } }
{ "_id" : ObjectId("516f202da1faf201daa15636"),
"url" : { "raw" : "https://github.com/Quasii",
"domain" : "github.com", "canonical" : "https://github.com/quasii" } }
> db.pGitHub.find().forEach(function(myProfile) {
var oldId = myProfile._id;
myProfile._id = 'exampleid';
db.pGitHub.save(myProfile);
db.pGitHub.remove({_id: oldId});
});
> db.pGitHub.find();
{ "_id" : ObjectId("516f204da1faf201daa15637"),
"url" : { "raw" : "https://github.com/Quatlus",
"domain" : "github.com", "canonical" : "https://github.com/quatlus" } }
{ "_id" : ObjectId("516f204da1faf201daa15638"),
"url" : { "raw" : "https://github.com/Quasii",
"domain" : "github.com", "canonical" : "https://github.com/quasii" } }
I'm using Mongo 2.4.2
Ben, your statements are correct. It's just mongo shell 2.4.2 behaves somehow different than others (server is not affected). You can use mongo shell binary from 2.4.1 for your purpose.
You can only set object IDs before they've been created. After the fact, they cannot be changed. What you're probably doing is creating new objects when you change the IDs like that.
There's more information in the MongoDB docs
I've "users" collection with a "watchlists" field, which have many inner fields too, one of that is "arrangeable_values" (the second field within "watchlists").
I need to find for each user in "users" collection, each "arrangeable_values" within "watchlists".
How can I do that with mongodb shell ?
Here is an example of data model :
> db.users.findOne({'nickname': 'superj'})
{
"_id" : ObjectId("4f6c42f6018a590001000001"),
"nickname" : "superj",
"provider" : "github",
"user_hash" : null,
"watchlists" : [
{
"_id" : ObjectId("4f6c42f7018a590001000002"),
"arrangeable_values" : {
"description" : "My introduction presentation to node.js along with sample code at various stages of building a simple RESTful web service with journey, cradle, winston, optimist, and http-console.",
"tag" : "",
"html_url" : "https://github.com/indexzero/nodejs-intro"
},
"avatar_url" : "https://secure.gravatar.com/avatar/d43e8ea63b61e7669ded5b9d3c2e980f?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
"created_at" : ISODate("2011-02-01T10:20:29Z"),
"description" : "My introduction presentation to node.js along with sample code at various stages of building a simple RESTful web service with journey, cradle, winston, optimist, and http-console.",
"fork_" : false,
"forks" : 13,
"html_url" : "https://github.com/indexzero/nodejs-intro",
"pushed_at" : ISODate("2011-09-12T17:54:58Z"),
"searchable_values" : [
"description:my",
"description:introduction",
"description:presentation",
"html_url:indexzero",
"html_url:nodejs",
"html_url:intro"
],
"tags_array" : [ ],
"watchers" : 75
},
{
"_id" : ObjectId("4f6c42f7018a590001000003"),
"arrangeable_values" : {
"description" : "A Backbone alternative idea",
"tag" : "",
"html_url" : "https://github.com/maccman/spine.todos"
},
"avatar_url" : "https://secure.gravatar.com/avatar/baf018e2cc4616e4776d323215c7136c?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png",
"created_at" : ISODate("2011-03-18T11:03:42Z"),
"description" : "A Backbone alternative idea",
"fork_" : false,
"forks" : 31,
"html_url" : "https://github.com/maccman/spine.todos",
"pushed_at" : ISODate("2011-11-20T22:59:45Z"),
"searchable_values" : [
"description:a",
"description:backbone",
"description:alternative",
"description:idea",
"html_url:https",
"html_url:github",
"html_url:com",
"html_url:maccman",
"html_url:spine",
"html_url:todos"
],
"tags_array" : [ ],
"watchers" : 139
}
]
}
For the document above, the following find() query would extract both the "nickname" of the document, and its associated "arrangeable_values" (where the document is in the users collection):
db.users.find({}, { "nickname" : 1, "watchlists.arrangeable_values" : 1 })
The result you get for your single document example would be:
{ "_id" : ObjectId("4f6c42f6018a590001000001"), "nickname" : "superj",
"watchlists" : [
{ "arrangeable_values" : { "description" : "My introduction presentation to node.js along with sample code at various stages of building a simple RESTful web service with journey, cradle, winston, optimist, and http-console.", "tag" : "", "html_url" : "https://github.com/indexzero/nodejs-intro" } },
{ "arrangeable_values" : { "description" : "A Backbone alternative idea", "tag" : "", "html_url" : "https://github.com/maccman/spine.todos" } }
] }
MongoDB queries return entire documents. You are looking for a field inside an array inside of the document and this will break the find().
The problem here is that any basic find() query, will return all matching documents. The find() does have the option to only return specific fields. But that will not work with your array of sub-objects. You could returns watchlists, but not watchlist entries that match.
As it stands you have two options:
Write some client-side code that loops through the documents and does the filtering. Remember that the shell is effectively a javascript driver, so you can write code in there.
Use the new aggregation framework. This will have a learning curve, but it can effectively extract the sub-items you're looking for.