Search for document that contains field from a given Array in MongoDB

Search for document that contains field from a given Array in MongoDB

In some cases you want to find all documents that some field of it are inside of a given array. To do so we will use the "$in" operator which takes an array as a value.

Let's say you have a collection named "articles" where you have the following two attributes "name" and "type" and you want to find the documents that their type in "snippets" or "articles" to show them to the end user.

Inserting documents

db.articles.insertMany([
{ type: "articles", name: "artciles 1" },
{ type: "snippets", name: "snippets 1" },
{ type: "issues", name: "issues 1" },
])

Search for fields in our array

db.articles.find({ type: { $in: ["snippets", "articles"] }})

Result

{ "_id" : ObjectId("5e31c643f098cf25b5b434ce"), "type" : "articles", "name" : "artciles 1" }
{ "_id" : ObjectId("5e31c643f098cf25b5b434cf"), "type" : "snippets", "name" : "snippets 1" }