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

后端 未结 12 2542
心在旅途
心在旅途 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:12

    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")})
    
    0 讨论(0)
  • 2020-11-28 02:13

    I think you better write something like this:

    db.getCollection('Blog').find({"_id":ObjectId("58f6724e97990e9de4f17c23")})
    
    0 讨论(0)
  • 2020-11-28 02:18

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

    db.theColl.find( { "_id": ObjectId("4ecbe7f9e8c1c9092c000027") } )
    
    0 讨论(0)
  • 2020-11-28 02:19

    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)

    0 讨论(0)
  • 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});
    
    0 讨论(0)
  • 2020-11-28 02:21

    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);
    
    0 讨论(0)
提交回复
热议问题