简体   繁体   中英

Get all documents with specific properties in MongoDB

Good morning everybody,

Today I'm facing with mongoose queries.

Let's suppose we have the following collection:

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

I'd like to get a sub-collection with the documents with name: "Books" and name: "Pencil".

Desired output:

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

Is it possible using the "find()" method?

You can use $in operator

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

Working Mongo playground

Another version of find using $or operator.

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

Here is MongoPlayground for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM