xfilipe
xfilipe

Reputation: 1

Problem using ObjectID in MongoDB Compass

I am learning to use MongoDB, I have created a cluster in the cloud at cloud.mongodb.com, and I connect to it with MongoDb Compass vs 1.22.1. I am trying to learn some basic commands, and I am trying to select items from my collection using the find() command to filter by id.

I have tried what I have seen being referenced everywhere, like:

db.recipes.find({_id: ObjectID("5e877cba20a4f574c0aa56da")});

or

db.recipes.find({'_id': ObjectID("5e877cba20a4f574c0aa56da")});

And I always get the output:

ReferenceError: ObjectID is not defined
    at evalmachine.<anonymous>:5:10
    at evalmachine.<anonymous>:7:3
    at Script.runInContext (vm.js:134:20)
    at Object.runInContext (vm.js:297:6)
    at ElectronInterpreterEnvironment.sloppyEval (C:\Users\lfili\AppData\Local\MongoDBCompass\app-1.22.1\resources\app.asar\node_modules\@mongodb-js\compass-shell\lib\index.js:140827:28)
    at Interpreter.<anonymous> (C:\Users\lfili\AppData\Local\MongoDBCompass\app-1.22.1\resources\app.asar\node_modules\@mongodb-js\compass-shell\lib\index.js:210735:41)
    at step (C:\Users\lfili\AppData\Local\MongoDBCompass\app-1.22.1\resources\app.asar\node_modules\@mongodb-js\compass-shell\lib\index.js:210685:19)
    at Object.next (C:\Users\lfili\AppData\Local\MongoDBCompass\app-1.22.1\resources\app.asar\node_modules\@mongodb-js\compass-shell\lib\index.js:210615:14)
    at C:\Users\lfili\AppData\Local\MongoDBCompass\app-1.22.1\resources\app.asar\node_modules\@mongodb-js\compass-shell\lib\index.js:210587:67
    at new Promise (<anonymous>)

If I dont use ObjectID, like:

db.recipes.find({'_id':"5e877cba20a4f574c0aa56da"});

I get no error but there is no output because I guess the _id is not "5e877cba20a4f574c0aa56da" but ObjectID("5e877cba20a4f574c0aa56da").

I don't know why can't use the ObjectID in the Compass MongoSH, any help would be welcome. Thank you

Upvotes: 0

Views: 2010

Answers (1)

Tiya Jose
Tiya Jose

Reputation: 1419

For newer versions you have to use

db.recipes.find({_id: ObjectId("5e877cba20a4f574c0aa56da")});

If you're using an older version before 1.10.x you can use:

db.recipes.find({"_id":{"$oid":"5e877cba20a4f574c0aa56da"}});

Upvotes: 2

Related Questions