ChatGPT解决这个技术问题 Extra ChatGPT

How do I search for an object by its ObjectId in the mongo console?

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.


T
Tyler Brock

Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.

Documentation is here

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

> db.test.find()                                               // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }      

> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c"))           // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }

Strange, I restarted my console and it suddenly worked. Is there some way to change your "scope" or something at the command line and not really know it?
No wonder: when I search for 'find ObjectID' that page didn't come up: mongodb.org/…
Yeah, you might have accidentally typed "use dbname" and switched databases. I'm assuming you are not using replication or sharding, which would obviously create other possibilities for why it wasn't showing up.
The issue was that I wasn't putting quotes around my _id.
Wow, I had no idea this was something special in MongoDB wasted a bit of time thinking my problem was elsewhere, but finding it just required additional rules. for what it's worth people using express and node will need to require ObjectId exp... var ObjectId = require('mongodb').ObjectID;
P
Phil

If you're using Node.js:

var ObjectId = require('mongodb').ObjectId; 
var id = req.params.gonderi_id;       
var o_id = new ObjectId(id);
db.test.find({_id:o_id})

Edit: corrected to new ObjectId(id), not new ObjectID(id)


import { ObjectId } from "mongodb"; works for fancier JS.
I not using Node.js at all. I don't understand the second line :( Any idea?
The second line is "_id" field value attached to the request parameter gonderi_id.
Works with the findOne command for prettier output.
R
Robert

Even easier, especially with tab completion:

db.test.find(ObjectId('4ecc05e55dd98a436ddcc47c'))

Edit: also works with the findOne command for prettier output.


if we want to search with multiple object Ids just like the way we implement WHERE IN condition in mysql.
This gives me an error: TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping
@DavidOkwii - this example is for the MongoShell. It looks like you're running from Python, in which case you would want to do something like: db.test.find({'_id': ObjectId('4ecc05e55dd98a436ddcc47c')})
This is wrong, using this approach in a db.test.findOneAndDelete(ObjectId('57eujhs76e7hs877e868')) command will delete a document even if the ObjectId does not match the specified id. You need to precisely specify like this db.test.find({'_id': ObjectId('4ecc05e55dd98a436ddcc47c')})
This question was about find(), not about findOneAndDelete().
M
Mohamed Abdullah J

You Have missed to insert Double Quotes. The Exact Query is

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

"The issue was that I wasn't putting quotes around my _id." -- Dec 7 2011, see the comments on the first answer
@jcollum As an update, the query you put now would be valid without the quotes around _id.
w
whoami - fakeFaceTrueSoul

If you are working on the mongo shell, Please refer this : Answer from Tyler Brock

I wrote the answer if you are using mongodb using node.js

You don't need to convert the id into an ObjectId. Just use :

db.collection.findById('4ecbe7f9e8c1c9092c000027');

this collection method will automatically convert id into ObjectId.

On the other hand :

db.collection.findOne({"_id":'4ecbe7f9e8c1c9092c000027'}) doesn't work as expected. You've manually convert id into ObjectId.

That can be done like this :

let id = '58c85d1b7932a14c7a0a320d';

let o_id = new ObjectId(id);   // id as a string is passed

db.collection.findOne({"_id":o_id});

findById should be a function/method from mongoose - where it internally converts string into ObjectId, unless you use mongoose this code doesn't help you whether it's node or other..!!
yes..i forgot to mention that mongoose is required..... thank you for the correction
P
Pang

I think you better write something like this:

db.getCollection('Blog').find({"_id":ObjectId("58f6724e97990e9de4f17c23")})

Can you explain a bit how this code answers the question?
O
Oliver Wolf

Once you opened the mongo CLI, connected and authorized on the right database.

The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:

db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})

P
Patrick Graham

I just had this issue and was doing exactly as was documented and it still was not working.

Look at your error message and make sure you do not have any special characters copied in. I was getting the error

SyntaxError: illegal character @(shell):1:43

When I went to character 43 it was just the start of my object ID, after the open quotes, exactly as I pasted it in. I put my cursor there and hit backspace nothing appeared to happen when it should have removed the open quote. I hit backspace again and it removed the open quote, then I put the quote back in and executed the query and it worked, despite looking exactly the same.

I was doing development in WebMatrix and copied the object id from the console. Whenever you copy from the console in WebMatrix you're likely to pick up some invisible characters that will cause errors.


K
Kushal Bhalaik

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

M
Miguel Peguero

To use Objectid method you don't need to import it. It is already on the mongodb object.

var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d'); db.yourCollection.findOne({ _id: ObjectId }, function (err, info) { console.log(info) });


Nope: TypeError: db.ObjectId is not a function
It's just ObjectId("SOMETHING")
U
Undo

Simply do:

db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');

This doesn't to work for me from Mongo Shell version 3.2.7.
That will only match an _id which is a string; if it is a true ObjectId, you need to search using the ObjectId syntax.