How to fetch data of multiple users in one query in mongodb?

Member

by lew , in category: MySQL , 22 days ago

How to fetch data of multiple users in one query in mongodb?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raphael_tillman , 22 days ago

@lew 

To fetch the data of multiple users in one query in MongoDB, you can use the $in operator in a find query. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const mongoose = require('mongoose');

const User = mongoose.model('User');

const userIds = ['user1_id', 'user2_id', 'user3_id'];

User.find({ _id: { $in: userIds } }, (err, users) => {
  if (err) {
    console.error(err);
  } else {
    console.log(users);
  }
});


In this example, we have an array of user IDs called userIds that we want to fetch data for. We use the $in operator in the find query to retrieve all users whose _id matches any of the user IDs in the userIds array.


This will return an array of user objects with the data for the specified user IDs.