MongoDB query to find on field combination of FirstName and LastName?


For combination, use $concat and check the equality using $eq. Let us create a collection with documents −

> db.demo502.insertOne({"FirstName":"John","LastName":"Smith"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e875534987b6e0e9d18f56d")
}
> db.demo502.insertOne({"FirstName":"David","LastName":"Miller"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e87553e987b6e0e9d18f56e")
}
> db.demo502.insertOne({"FirstName":"John","LastName":"Doe"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e875543987b6e0e9d18f56f")
}

Display all documents from a collection with the help of find() method −

> db.demo502.find();

This will produce the following output −

{ "_id" : ObjectId("5e875534987b6e0e9d18f56d"), "FirstName" : "John", "LastName" : "Smith"
}
{ "_id" : ObjectId("5e87553e987b6e0e9d18f56e"), "FirstName" : "David", "LastName" : "Miller"
}
{ "_id" : ObjectId("5e875543987b6e0e9d18f56f"), "FirstName" : "John", "LastName" : "Doe" }

Following is the query to find on field combination −

> db.demo502.aggregate(
...    [
...       { "$redact": {
...          "$cond": [
...             { "$eq": [
...                { "$concat": [ "$FirstName", " ", "$LastName" ] },
...                "John Doe"
...             ]},
...             "$$KEEP",
...             "$$PRUNE"
...          ]
...       }}
...    ]
... )

This will produce the following output −

{ "_id" : ObjectId("5e875543987b6e0e9d18f56f"), "FirstName" : "John", "LastName" : "Doe" }

Updated on: 13-May-2020

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements