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

后端 未结 12 2622
心在旅途
心在旅途 2020-11-28 01:58

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(\"4ecbe7f9e8c

12条回答
  •  盖世英雄少女心
    2020-11-28 02:21

    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});
    

提交回复
热议问题