Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB query to find documents with specific FirstName and LastName
To find documents with specific FirstName and LastName, use $and along with $in. Implement this in MongoDB find(). Let us create a collection with documents −
> db.demo692.insertOne({FirstName:"Chris","LastName":"Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585dca7e81adc6a0b396a")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585e2a7e81adc6a0b396b")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585e7a7e81adc6a0b396c")
}
> db.demo692.insertOne({FirstName:"John","LastName":"Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585efa7e81adc6a0b396d")
}
> db.demo692.insertOne({FirstName:"Adam","LastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea585faa7e81adc6a0b396e")
}
Display all documents from a collection with the help of find() method −
> db.demo692.find();
This will produce the following output −
{ "_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" }
Following is the query to find documents with specific FirstName and LastName −
> db.demo692.find({$and:[ {FirstName: {$in: ["Chris", "John"]}},
... {LastName:{$in:["Brown", "Smith"]}}
... ]
... }
... );
This will produce the following output −
{ "_id" : ObjectId("5ea585dca7e81adc6a0b396a"), "FirstName" : "Chris", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e2a7e81adc6a0b396b"), "FirstName" : "John", "LastName" : "Brown" }
{ "_id" : ObjectId("5ea585e7a7e81adc6a0b396c"), "FirstName" : "John", "LastName" : "Smith" }Advertisements