Search for arrays that contains a given value in MongoDB

Search for arrays that contains a given value in MongoDB

In some cases you want to find all documents that some arrays of it contains a given value. Read the next examples to know how.

Let's say you have a collection named "articles" where you have the following two attributes "name" and "types" and you want to find the documents that their types field contains the value "snippets".

Inserting Documents

db.articles.insertMany([
{ types: ["articles", "snippets"] , name: "article 1" },
{ types: ["errors", "snippets", "issues"], name: "article 1" },
{ types: ["issues"], name: "article 1" },
])

Search for documents containing the value

db.articles.find({ types: "snippets" })

Result

{ "_id" : ObjectId("5e31c92cf098cf25b5b434d1"), "types" : [ "articles", "snippets" ], "name" : "article 1" }
{ "_id" : ObjectId("5e31c92cf098cf25b5b434d2"), "types" : [ "errors", "snippets", "issues" ], "name" : "article 1" }