MongoDB query to fetch only the “Name” field based on roles?

MongoDBDatabaseBig Data Analytics

For this, use aggregate(). Here, we have considered 3 roles − Admin, Guest, and User. Let us create a collection with documents −

> db.demo532.insertOne({"Name":"Chris","Type":"Admin"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4a9def4dcbee04fbbbf9")
}
> db.demo532.insertOne({"Name":"David","Type":"Guest"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4aa3ef4dcbee04fbbbfa")
}
> db.demo532.insertOne({"Name":"Bob","Type":"User"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8b4ab0ef4dcbee04fbbbfb")
}

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

> db.demo532.find();

This will produce the following output −

{ "_id" : ObjectId("5e8b4a9def4dcbee04fbbbf9"), "Name" : "Chris", "Type" : "Admin" }
{ "_id" : ObjectId("5e8b4aa3ef4dcbee04fbbbfa"), "Name" : "David", "Type" : "Guest" }
{ "_id" : ObjectId("5e8b4ab0ef4dcbee04fbbbfb"), "Name" : "Bob", "Type" : "User" }

Following is the query to get a unique document which needs to be compared with other documents in the same collection −

> db.demo532.aggregate([
...    {$group: {_id:"$Name", "types":{$addToSet:"$Type"}}},
...    {$project: {_id:1, "types": 1, "isSubset": { $setIsSubset: [ ["Admin"], "$types" ] }}},
...    {$match: {"isSubset": false}},
...    {$group: {_id:"$isSubset", "Name": {$push : "$_id"}}},
...    {$project: {"_id": 0, "Name": 1}},
...    {$unwind: "$Name"}
... ])

This will produce the following output −

{ "Name" : "David" }
{ "Name" : "Bob" }
raja
Published on 14-May-2020 09:52:34
Advertisements