在MongoDB中获取具有特定属性的所有文档

时间:2020-09-21 10:34:53

标签: javascript mongodb express mongoose mongodb-query

大家早上好,

今天我正面临猫鼬查询。

假设我们有以下集合:

[
   {letter: "A", name: "Books", action: "read"},
   {letter: "B", name: "Notebook", action: "write"},
   {letter: "C", name: "Camera", action: "take photos"},
   {letter: "D", name: "Pencil", action: "draw"}
]

我想得到一个子集合,其文档名称为“ Books”,名称为“ Pencil”。

所需的输出:

[
       {letter: "A", name: "Books", action: "read"},
       {letter: "D", name: "Pencil", action: "draw"}
]

是否可以使用“ find()”方法?

2 个答案:

答案 0 :(得分:1)

您可以使用$in运算符

db.collection.find({
  name: {
    $in: [
      "Books",
      "Pencil"
    ]
  }
})

工作Mongo playground

答案 1 :(得分:1)

使用find运算符的$or的另一个版本。

db.collection.find({
  $or: [
    {
      "name": "Books"
    },
    {
      "name": "Pencil"
    }
  ]
})

给您MongoPlayground