Reputation: 14189
I have a collection which have a document like this:
collection 1
{
_id: ObjectID(),
name: foo
}
I would get ObjectID of the above collection and copy into a document of another collection in order to reference correctly. Should I do simply:
db.collection1.find({name:"foo"},{_id:1})
EDIT
Upvotes: 0
Views: 594
Reputation: 10473
A call to find
will return a cursor. Cursors works like an iterator in other languages. You can either attempt to find the first element in the cursor using the next()
function and then get it's _id
property or simplify your statement using findOne
:
var x = db.collection1.findOne({name:"foo"}, {_id:1});
var id = x._id;
This is making an assumption that you are getting a document back from that query. You'll probably want to add a null
check on x
before grabbing the _id
property.
Upvotes: 2