Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query to find documents with specific FirstName and LastName
To find documents with specific FirstName and LastName in MongoDB, use the $and operator along with $in to match multiple values for each field. This allows you to query for documents that match any combination of the specified first and last names.
Syntax
db.collection.find({
$and: [
{FirstName: {$in: ["name1", "name2"]}},
{LastName: {$in: ["surname1", "surname2"]}}
]
});
Create Sample Data
db.demo692.insertMany([
{FirstName: "Chris", LastName: "Brown"},
{FirstName: "John", LastName: "Brown"},
{FirstName: "John", LastName: "Smith"},
{FirstName: "John", LastName: "Doe"},
{FirstName: "Adam", LastName: "Smith"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5ea585dca7e81adc6a0b396a"),
ObjectId("5ea585e2a7e81adc6a0b396b"),
ObjectId("5ea585e7a7e81adc6a0b396c"),
ObjectId("5ea585efa7e81adc6a0b396d"),
ObjectId("5ea585faa7e81adc6a0b396e")
]
}
Display All Documents
db.demo692.find();
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5ea585efa7e81adc6a0b396d"), "FirstName" : "John", "LastName" : "Doe" }
{ "_id" : ObjectId("5ea585faa7e81adc6a0b396e"), "FirstName" : "Adam", "LastName" : "Smith" }
Example: Find Specific FirstName and LastName Combinations
Find documents where FirstName is either "Chris" or "John" AND LastName is either "Brown" or "Smith" ?
db.demo692.find({
$and: [
{FirstName: {$in: ["Chris", "John"]}},
{LastName: {$in: ["Brown", "Smith"]}}
]
});
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }
How It Works
The query returns documents where:
- Chris Brown − matches both conditions
- John Brown − matches both conditions
- John Smith − matches both conditions
- John Doe − excluded (LastName "Doe" not in the specified list)
- Adam Smith − excluded (FirstName "Adam" not in the specified list)
Conclusion
Use $and with $in operators to find documents matching specific combinations of FirstName and LastName values. This approach efficiently filters documents based on multiple field criteria.
Advertisements
