Tavinder Singh
Tavinder Singh

Reputation: 420

How to find from multiple values in mongodb

There is a collection in MongoDB like:

{
    "_id" : ObjectId("5bcc4c7d1e2c701be024de99"),
    "className" : "Class 10",
    "gradeLevel" : "10th",
    "subjectName" : "Math",
    "teacherId" : "[email protected]",
    "__v" : 0
},
{
    "_id" : ObjectId("5bd45277f5b9430013f4a604"),
    "className" : "Class 11",
    "gradeLevel" : "11th",
    "subjectName" : "Maths",
    "teacherId" : "[email protected]",
    "__v" : 0
},
{
    "_id" : ObjectId("5bd470fe452cb33af4b8407a"),
    "className" : "Class 10",
    "gradeLevel" : "12th",
    "subjectName" : "Math",
    "teacherId" : "[email protected]",
    "__v" : 0
},

Now I want to fetch those documents with values of_id: ObjectId("5bd45277f5b9430013f4a604"), ObjectId("5bd470fe452cb33af4b8407a").

I am using mongoose and node.js. So please tell me is there any way to do this.

Upvotes: 2

Views: 7550

Answers (2)

Rafiq
Rafiq

Reputation: 11465

https://mongoplayground.net/p/6o9UbqxADPp

if you want to match multiple condition

[
  {
    "key": 1,
    "sk": 5
  },
  {
    "key": 2,
    "sk": 7
  },
  {
    "key": 3,
    "sk": 8
  }
]

db.collection.find({
  "$or": [
    {
      "$and": [
        {
          "key": 1
        },
        {
          "sk": 5
        }
      ]
    },
    {
      "$and": [
        {
          "key": 2
        },
        {
          "sk": 7
        }
      ]
    }
  ]
})

Upvotes: 0

Asaf Aviv
Asaf Aviv

Reputation: 11770

Model.find({ _id: { $in: ['5bd45277f5b9430013f4a604', '5bd470fe452cb33af4b8407a'] } })
  .then(docs => console.log(docs))
  .catch(err => console.log(err));

Upvotes: 6

Related Questions