mongodb/mongoose findMany - find all documents with IDs listed in array

node.jsMongodbMongooseFiltering

node.js Problem Overview


I have an array of _ids and I want to get all docs accordingly, what's the best way to do it ?

Something like ...

// doesn't work ... of course ...

model.find({
    '_id' : [
	    '4ed3ede8844f0f351100000c',
	    '4ed3f117a844e0471100000d', 
	    '4ed3f18132f50c491100000e'
    ]
}, function(err, docs){
    console.log(docs);
});

The array might contain hundreds of _ids.

node.js Solutions


Solution 1 - node.js

The find function in mongoose is a full query to mongoDB. This means you can use the handy mongoDB $in clause, which works just like the SQL version of the same.

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});

This method will work well even for arrays containing tens of thousands of ids. (See Efficiently determine the owner of a record)

I would recommend that anybody working with mongoDB read through the Advanced Queries section of the excellent Official mongoDB Docs

Solution 2 - node.js

Ids is the array of object ids:

const ids =  [
    '4ed3ede8844f0f351100000c',
    '4ed3f117a844e0471100000d', 
    '4ed3f18132f50c491100000e',
];

Using Mongoose with callback:

Model.find().where('_id').in(ids).exec((err, records) => {});

Using Mongoose with async function:

const records = await Model.find().where('_id').in(ids).exec();

Or more concise:

const records = await Model.find({ '_id': { $in: ids } });

Don't forget to change Model with your actual model.

Solution 3 - node.js

Combining Daniel's and snnsnn's answers:

let ids = ['id1','id2','id3']
let data = await MyModel.find(
  {'_id': { $in: ids}}
);

Simple and clean code. It works and tested against:

"mongodb": "^3.6.0", "mongoose": "^5.10.0",

Solution 4 - node.js

Use this format of querying

let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));

Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
  .where('category')
  .in(arr)
  .exec();

Solution 5 - node.js

This code works for me just fine as of mongoDB v4.2 and mongoose 5.9.9:

const Ids = ['id1','id2','id3']
const results = await Model.find({ _id: Ids})

and the Ids can be of type ObjectId or String

Solution 6 - node.js

Both node.js and MongoChef force me to convert to ObjectId. This is what I use to grab a list of users from the DB and fetch a few properties. Mind the type conversion on line 8.

// this will complement the list with userName and userPhotoUrl based on userId field in each item
augmentUserInfo = function(list, callback){
        var userIds = [];
        var users = [];         // shortcut to find them faster afterwards
        for (l in list) {       // first build the search array
            var o = list[l];
            if (o.userId) {
                userIds.push( new mongoose.Types.ObjectId( o.userId ) );           // for the Mongo query
                users[o.userId] = o;                                // to find the user quickly afterwards
            }
        }
        db.collection("users").find( {_id: {$in: userIds}} ).each(function(err, user) {
            if (err) callback( err, list);
            else {
                if (user && user._id) {
                    users[user._id].userName = user.fName;
                    users[user._id].userPhotoUrl = user.userPhotoUrl;
                } else {                        // end of list
                    callback( null, list );
                }
            }
        });
    }

Solution 7 - node.js

I tried like below and its works for me.

var array_ids=['1','2','6','9'] // your array of ids
model.find({ '_id': { $in: array_ids }}).toArray(function(err, data) {
            if (err) {
                logger.winston.error(err);
            } else {
                console.log("data", data);
            }
        });

Solution 8 - node.js

if you are using the async-await syntax you can use

const allPerformanceIds = ["id1", "id2", "id3"];
const findPerformances = await Performance.find({ _id: { $in: allPerformanceIds } });
           

Solution 9 - node.js

I am using this query to find the files in mongo GridFs. I wanted to get the by its Ids.

For me this solution is working: Ids type of ObjectId.

gfs.files
.find({ _id: mongoose.Types.ObjectId('618d1c8176b8df2f99f23ccb') })
.toArray((err, files) => {
  if (!files || files.length === 0) {
    return res.json('no file exist');
  }
  return res.json(files);
  next();
});

This is not working: Id type of string

gfs.files
.find({ _id: '618d1c8176b8df2f99f23ccb' })
.toArray((err, files) => {
  if (!files || files.length === 0) {
    return res.json('no file exist');
  }
  return res.json(files);
  next();
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionezmilhouseView Question on Stackoverflow
Solution 1 - node.jsDaniel MendelView Answer on Stackoverflow
Solution 2 - node.jssnnsnnView Answer on Stackoverflow
Solution 3 - node.jsAhmad AgbaryahView Answer on Stackoverflow
Solution 4 - node.jsDerese GetachewView Answer on Stackoverflow
Solution 5 - node.jsfafa.mnzmView Answer on Stackoverflow
Solution 6 - node.jsNicoView Answer on Stackoverflow
Solution 7 - node.jsUma Devi HariramView Answer on Stackoverflow
Solution 8 - node.jsMD SHAYONView Answer on Stackoverflow
Solution 9 - node.jsTiny BotView Answer on Stackoverflow