Home > Software engineering >  Best way to find all documents with 2 fields in mongoDb
Best way to find all documents with 2 fields in mongoDb

Time:05-24

i need help in finding documents in mongodb. My schema is like below:

const users = new Schema({
      _id: ObjectId,
      facebookId: String,
      .....
      .....
})

I have 2 arrays for query like below:

const facebookIds = ['1', '2', '3']
const _ids = ['1', '2', '3']

At the moment, I am thinking of finding all the documents with facebookIds array first, getting their _id, concat the result with _ids array, and finally finding all the documents with resultant _ids array.

So, I want to know that what will be the best way to query the documents in one go, or this is the only way.

Thanks in advance.

CodePudding user response:

Assuming you have 3 users in the collection with facebookId and another 3 without facebookId. You already have the facebookId of the first 3 data and _id of the last 3 data.

    [
  {
    _id: 1,
      facebookId: 10,
  },
  {
    _id: 2,
      facebookId: 20,
  },
  {
    _id: 3,
      facebookId: 10,
  },
  {
    _id: 4,
      facebookId: null,
  },
  {
    _id: 5,
      facebookId: null,
  },
  {
    _id: 6,
      facebookId: null,
  }
]

You can use $or operator and $in operator for this

db.collection.find({
  $or: [
    {
      facebookId: {
        $in: [10,20,30]
      }
    },
    {
      _id: {
        $in: [4,5,6]
      }
    }
  ]
})

Here is a working mongoplayground link

  • Related