Reassign MongoDB _id in shell - mongodb

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

Related

MongoDB Check if a Collection contains a Key

I am using the MongoDB Async Driver to create a little Program were i have to save a User-Profile in the Database.
So i have a Database looking like this
`{
"_id" : ObjectId("5a1743f086060f1bbc319cdb"),
"id" : "aUser1",
"SomeArray" : {
"Name" : "SomeName"
}
}
{
"_id" : ObjectId("5a1743f186060f1bbc319cdc"),
"id" : "aUser2",
"SomeArray" : {
"Name" : "SomeName"
}
}
{
"_id" : ObjectId("5a1743f286060f1bbc319cdd"),
"id" : "aUser3",
"SomeArray" : {
"Name" : "SomeName"
}
}`
And now i try to figure out if the User 1 already has created a Profile.
Whith the old driver i would know how but with the , for me new, Async-Driver it sems a little bit tricky, do i have to make an Callback for this ?

MongoDB DBReference how to?

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/

MongoDB .Net driver 2.0 Builders Filter (field to array comparison)

I need to get all usernames from "followingList.username" and compare with
posts' usernames, if there any match need to add that one to an array.
Person Model
{
"_id" : ObjectId("554f20f5c90d3c7ed42303e1"),
"username" : "fatihyildizhan",
"followingList" : [
{
"_id" : ObjectId("55505b6ca515860cbcf7901d"),
"username" : "gumusluk",
"avatar" : "avatar.png"
},
{
"_id" : ObjectId("58505b6ca515860cbcf7901d"),
"username" : "yalikavak",
"avatar" : "avatar.png"
},
{
"_id" : ObjectId("58305b6ca515860cbcf7901d"),
"username" : "gumbet",
"avatar" : "avatar.png"
}
]
}
Post Model
{
"_id" : ObjectId("554f2df2a388R4b425b89833"),
"username" : "yalikavak",
"category" : "Summer",
"text" : "blue voyage with yacht"
},
{
"_id" : ObjectId("554f2df2a388P4b425b89833"),
"username" : "yalikavak",
"category" : "Winter",
"text" : "is coming ..."
},
{
"_id" : ObjectId("554f2df2a388K4b425b89833"),
"username" : "gumbet",
"category" : "Fall",
"text" : "there are many trees"
}
I try to get result code block as below but couldn't figure it out.
var filter = Builders<Post>.Filter.AnyEq("username", usernameList);
var result = collection.Find(filter).ToListAsync().Result;
Can you help me with this?
Thanks.
The logic is flipped, what you need is an $in query if I understand your use case correctly:
var filter = Builders<Post>.Filter.In("username", usernameList);
var result = collection.Find(filter).ToListAsync().Result;
In your case, username is a simple field and you want to match against a list of candidates. AnyEq is used to check that, from an embedded list of complex objects, at least one matches a criterion. That still translates to a simple query in MongoDB, but requires to 'reach into' the object which needs a more complicated syntax.

MongoDb - Query for specific subdocument

I have a set of mongodb documents with the following structure:
{
"_id" : NUUID("58fbb893-dfe9-4f08-a761-5629d889647d"),
"Identifiers" : {
"IdentificationLevel" : 2,
"Identifier" : "extranet\\test#test.com"
},
"Personal" : {
"FirstName" : "Test",
"Surname" : "Test"
},
"Tags" : {
"Entries" : {
"ContactLists" : {
"Values" : {
"0" : {
"Value" : "{292D8695-4936-4865-A413-800960626E6D}",
"DateTime" : ISODate("2015-04-30T09:14:45.549Z")
}
}
}
}
}
}
How can I make a query with the mongo shell which finds all documents with a specific "Value" (e.g.{292D8695-4936-4865-A413-800960626E6D} in the Tag.Entries.ContactLists.Values path?
The structure is unfortunately locked by Sitecore, so it is not an options to use another structure.
As your sample collection structure show Values is object, it contains only one Value. Also you must check for Value as it contains extra paranthesis. If you want to get Value from given structure try following query :
db.collection.find({
"Tags.Entries.ContactLists.Values.0.Value": "{292D8695-4936-4865-A413-800960626E6D}"
})

Mongo database Query

I'm new to mongo database.Please help me in writing the query updation. I already had a collection in mongo and i would like to add a new field in existing object field.the structure is as follows.
{
"_class" : "PersistentContent",
"originalId" : "2070",
"videoInfo" : {
"test1" : ["res"]
},
}
I would like to update the structure to below format.
{
"_class" : "PersistentContent",
"originalId" : "2070",
"videoInfo" : {
"test1" : ["res"],
"test2" : ["res2"]
},
}
How to update the collection and add test2 into videoInfo tag.
use
db.test.update({"originalId" : "2070"},
{
$set : { "videoInfo.test2" : ["res2"] }
})