mongoose 如何在mongodb中从多个值中查找

2o7dmzc5  于 12个月前  发布在  Go
关注(0)|答案(2)|浏览(116)

在MongoDB中有一个集合:

{
    "_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
},

现在我想获取那些值为_id的文档:ObjectId(“5bd45277f5b9430013f4a604”)、ObjectId(“5bd470fe452cb33af4b8407a”)。
我用的是mongoose和node.js。所以请告诉我有什么办法可以做到这一点。

vshtjzan

vshtjzan1#

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

hmae6n7t2#

https://mongoplayground.net/p/6o9UbqxADPp
如果要匹配多个条件

[
  {
    "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
        }
      ]
    }
  ]
})

相关问题