w3resource

Finding Documents in MongoDB with an Array containing a specific value

Find MongoDB Document with Array containing specific value

To find a document with an array that contains a specific value in MongoDB, you can use a straightforward query where you specify the array field and the value you want to check for. MongoDB’s query language allows you to match documents with arrays that contain specific values easily. Here’s how to do it, with syntax, example code, and an explanation.

In MongoDB, finding documents with an array that contains a specific value is achieved by directly querying the array field with the desired value. MongoDB will check each array element, and if the value exists in any element of the array, it will return that document. This query method is efficient and easy to use.

Syntax:

The syntax for querying an array that contains a specific value is:

{ <array_field>: <value> }

Explanation:

  • <array_field>: The name of the array field you want to search within.
  • <value>: The specific value you’re looking for within the array.

Example Code:

Here's an example that queries a products collection to find all documents where the tags array field contains the value "electronics".

Code:

// Query the 'products' collection
db.products.find(
  {
    // Find documents where 'tags' array contains 'electronics'
    tags: "electronics"
  }
)

Explanation:

  • db.products.find(...)
    This command initiates a query in the products collection.
  • { tags: "electronics" }
    Inside the find method, this query filters documents where the tags array field contains the exact value "electronics".

MongoDB will go through each document in the products collection, and if any document’s tags array includes "electronics", that document will be returned.

This method is simple and effective for cases where you want to check if a specific value exists within an array field in MongoDB.

Practical Guides to MongoDB Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/snippets/find-mongodb-document-with-array-containing-specific-value.php