How to Find Document with Array that Contains a Specific Value in MongoDB
Last Updated :
26 Mar, 2024
MongoDB is a popular choice for developers working with large volumes of data, due to its flexibility and powerful querying capabilities. One common task developers face is finding documents in a collection where an array field contains a specific value.
In this beginner-friendly article, we'll explore simple yet effective methods to achieve this using MongoDB.
How to Find a Document with Array that Contains Specific Value in MongoDB?
In MongoDB, the find() method selects the documents in a collection and returns the cursor to the selected documents. A cursor means pointer and how it is pointing to a document, when we use the find() method it returns a pointer on the selected documents and returns one by one.
These find() methods can have the ability to access single or multiple documents in the collection.
The syntax is as follows:
db.Collection_name.find(selection, projection,options)
Explanation:
- selection: It is used to select required documents. To select all documents in the collection, we can remove the parameter or use collection_name.find().
- projection: It is used to specify which fields are to be returned in the documents based on our requirements. To return all fields in the matching documents, remove this parameter.
- options: It specifies some additional options for the parameter and modifies the behavior in selection.
Examples: Find Document with Array that Contains a Specific Value in MongoDB
Example 1
Let's Create a MongoDB collection named Specificvalue
and insert sample documents into the collection. Display all documents from the collection and find a document where the FavouriteSubject
field contains the value "MongoDB"
// Inserting sample documents into the collection
db.Specificvalue.insertMany( [
{ "StudentId":1,
"StudentName":"Larry",
"FavouriteSubject":["C","C++","Java"]
} ,
{ "StudentId":2,
"StudentName":"Larry",
"FavouriteSubject":["MongoDB","MySQL","SQL Server"]
}
] );
// Display all documents from the collection
db.Specificvalue.find();
// Finding specific value
db.Specificvalue.find({FavouriteSubject: "MongoDB"});
Output:
OutputExplanation: In the above output, we finded a document based on specific value is equal FavouriteSubject: "MongoDB" by using the find() function.
Example 2
Let's Create a MongoDB collection named games
, insert the provided sample documents. Then, display all documents from the collection and find a document where the team
field contains the value "csk".
// Inserting sample documents into the collection
db.games.insertMany([
{
player: 1,
name: "Rahul",
game: "kabaddi",
team:"Telugu titans",
age: 26,
league: "PKL",
guests: ["hero", "heroine"]
},
{
player: 2,
name: "dhoni",
game: "Cricket",
team: "csk",
age: 43,
league: "IPL",
guests: ["cm", "pm"]
}
])
// displaying all the documents
db.games.find()
//displaying specific value
db.games.find({team:"csk"})
Output:
OutputExplanation: In the below output, we finded a document based on specific value which is equal to team:"csk" by using the find() function.
Example 3
Let's Insert the provided student details into a MongoDB collection named student_details
. Display all documents from the collection and find documents where the age
field is equal to 20.
// Inserting sample documents into the collection
db.student_details.insertMany([
{
student: 1,
Name: "Bhaskar",
age: 20,
sex: "Male",
id_no: 102,
college_name: "Sri sai"
},
{
student: 2,
Name: "Bhanu priya",
age: 19,
sex: "Female",
id_no: 103,
college_name: "vishnu"
},
{
student: 3,
Name: "Gopi",
age: 20,
sex: "Male",
id_no: 104,
college_name: "Raghu"
}
]);
// Displaying all the documents
db.student_details.find();
// Displaying specific value
db.student_details.find({ age: 20 });
Output:
OutputExplanation: In the above output, we finded a document based on specific value is equal to "age:20" by using the find() function.
Conclusion
Overall, Finding documents in a collection where an array field contains a specific value is a common requirement.By using the find()
method with appropriate parameters, developers can easily select the required documents from a collection.
The selection
parameter allows for the selection of specific documents, while the projection
parameter specifies which fields to return in the result.In this article, we explored several examples to demonstrate how to find documents with arrays containing specific values in MongoDB.
Similar Reads
How to Select a Single Field for all Documents in a MongoDB Collections
In MongoDB, retrieving specific data from a collection is a common operation that developers often perform. Whether we are building a web application or running analytical queries, selecting a single field from all documents in a MongoDB collection can provide valuable insights and simplify data pro
3 min read
How to Query for Documents Where Array Size is Greater Than 1 in MongoDB
MongoDB's flexibility in managing arrays within documents is invaluable for modern applications. Sometimes, we might need to find documents where an array field contains more than one element. Hereâs how you can achieve this using MongoDB queries In this article, We will various methods through whic
4 min read
How to Find MongoDB Records Where the Array Field is Empty?
In MongoDB, effectively managing arrays within documents is important for handling flexible and dynamic data structures. However, querying for documents with empty array fields can sometimes be challenging. In this article, we will learn about How to find MongoDB records where the array field is emp
4 min read
How to find all the document keys of MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term âNoSQLâ means ânon-relationalâ. It means that MongoDB isnât based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This fo
1 min read
How to find Objects Containing Matching Elements from Arrays in Another Object ?
The task is to find objects that contain matching elements from arrays in another object. An object containing an array of values and a separate object. The objective is to determine whether the values present in the array are also present as keys in the separate object. These are the following meth
4 min read
How to Retrieve only the Queried Element in an Object Array in MongoDB Collection
In MongoDB, retrieving specific elements from an object array within a document is a common requirement, especially when dealing with complex data structures. MongoDB provides powerful query operators to filter and retrieve only the elements that match certain criteria within an array. This capabili
4 min read
How to Find Items Without a Certain Field in MongoDB
In MongoDB, querying for documents that don't have a certain field can be a common requirement, especially when dealing with schemaless data. While MongoDB provides various querying capabilities, finding documents without a specific field can sometimes be difficult. In this article, we'll explore di
4 min read
How to count total number of unique documents in MongoDB using Node.js ?
MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Insta
1 min read
How to Find Documents by ID in MongoDB?
In MongoDB, finding documents by their unique identifier (ID) is a fundamental operation that allows us to retrieve specific records efficiently. Each document in a MongoDB collection has a unique _id field, which serves as the primary key. In this article, we will explore how to find documents by I
3 min read
How to Check if an Array Field Contains a Unique Value or Another Array in MongoDB?
MongoDB is a widely used NoSQL database that enables developers to query complex data structures flexibly. In MongoDB, arrays are commonly used to store lists of values, providing flexibility in data modeling. To ensure data integrity and get valuable insights, it's important to understand how to ch
4 min read