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

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

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

    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.

    0 讨论(0)
  • 2020-11-28 02:30

    If you're using Node.js:

    In that req.user is ObjectId format.

    var mongoose = require("mongoose");
    var ObjectId = mongoose.Schema.Types.ObjectId;
    
    function getUsers(req, res)
        User.findOne({"_id":req.user}, { password: 0 }) 
             .then(data => { 
                 res.send(data);})g
    }
    exports.getUsers = getUsers;
    
    0 讨论(0)
  • 2020-11-28 02:33

    Simply do:

    db.getCollection('test').find('4ecbe7f9e8c1c9092c000027');
    
    0 讨论(0)
  • 2020-11-28 02:37

    Even easier, especially with tab completion:

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

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

    0 讨论(0)
  • 2020-11-28 02:38

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

    0 讨论(0)
提交回复
热议问题