MongoDB query to find documents with specific FirstName and LastName

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 14-May-2020 12:43:48
Advertisements