123

is possible in mongo db to select collection's documents like in SQL :

SELECT * FROM collection WHERE _id IN (1,2,3,4);

or if i have a _id array i must select one by one and then recompose the array/object of results?

6 Answers 6

242

Easy :)

db.collection.find( { _id : { $in : [1,2,3,4] } } );

taken from: https://www.mongodb.com/docs/manual/reference/operator/query/in/#mongodb-query-op.-in

Sign up to request clarification or add additional context in comments.

5 Comments

Do we still get benefits of indexing? IDs in that case are passed as plain strings...
You do. However time complexity is linear (n), not logarithmic/constant. Without index it would be n^2.
Is it not O(log(n) * m) where n is the size of the collection and m is the number of ids passed ?
U have to use ObjectId function, if "_id" is the ID object — {_id: {$in: [ObjectId("5a633609670aeb6f93b88b23")]}}
And nowadays, you need new ObjectId(...).
17

Because mongodb uses bson and for bson is important attribute types. and because _id is ObjectId you must use like this:

db.collection.find( { _id : { $in : [ObjectId('1'),ObjectId('2')] } } );

and in mongodb compass use like this:

{ "_id" : { $in : [ObjectId('1'),ObjectId('2')] } }

Note: objectId in string has 24 length.

Comments

8

You can try this

var ids = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"];

var oids = [];
ids.forEach(function(item){
oids.push(new ObjectId(item));
});

.find({ _id: {$in : oids}})

1 Comment

Thanks. Remember to define ObjectID like this: var ObjectId = require('mongodb').ObjectID;
6

list is a array of ids

In this code list is the array of ids in user collection

var list = ["5883d387971bb840b7399130","5883d389971bb840b7399131","5883d38a971bb840b7399132"]

    .find({ _id: {$in : list}})

2 Comments

The code is not working. It seems have to set IDs as ObjectId("5883d387971bb840b7399130")
How do we do set them to ObjectIds programmatically? I tried the approach suggested by @klipmode in one of the answers, but that does not work.
1

The query should be something like this:

db.collection.find( { 
        "_id": {
            "$in": [
                "475B9A5029D21",
                "385D808029D81",
                "C3463BD029DBB",
                "B839DB5029FFF"
            ]
        }
 } );

Comments

0

if you want to find by user and also by another field like conditionally, you can easily do it like beneath with spread and ternary operator using aggregate and match

 const p_id = patient_id;
    let fetchingReports = await Reports.aggregate([
      ...(p_id
        ? [
            {
              $match: {
                createdBy: mongoose.Types.ObjectId(id),
                patient_id: p_id,
              },
            },
          ]
        : [
            {
              $match: {
                createdBy: mongoose.Types.ObjectId(id),
              },
            },
        

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.