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

MongoDBDatabaseBig Data Analytics

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" }
raja
Published on 13-May-2020 06:22:28
Advertisements