0 votes
1 view
in Web Technology by (47.8k points)

I've found this question answered for C# and Perl, but not in the native interface. I thought this would work:

db.theColl.find( { _id: ObjectId("4ecbe7f9e8c1c9092c000027") } )

The query returned no results. I found the 4ecbe7f9e8c1c9092c000027 by doing db.theColl.find()and grabbing an ObjectId. There are several thousand objects in that collection.

I've read all the pages that I could find on the mongodb.org website and didn't find it. Is this just a strange thing to do? It seems pretty normal to me.

2 Answers

0 votes
by (107k points)

You can use the below-mentioned code to search for an object by its ObjectId in the console:-

> db.test.insert({x: 1}) 

> db.test.find() 

{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 } 

> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) 

{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 } 

> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c")) 

{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

0 votes
by (80.9k points)

If you're using Node.js, you can apply the following command:

> var ObjectId = require('mongodb').ObjectId; 

> var id = req.params.gonderi_id;       

> var o_id = new ObjectId(id);

> db.test.find({_id:o_id})

Welcome to Intellipaat Community. Get your technical queries answered by top developers !