Reputation: 1113
I am having mongodb data like this
{
"_id" : ObjectId("58eb32fb58bbf720a80daf6f"),
"RoleName" : "Admin",
"UIList" : [
{
"UiName" : "ManageRole",
"View" : true,
"Edit" : false,
"_id" : ObjectId("58eb32fb58bbf720a80daf79")
},
{
"UiName" : "ManageBuildings",
"View" : false,
"Edit" : false,
"_id" : ObjectId("58eb32fb58bbf720a80daf78")
},
{
"UiName" : "ManageFacility",
"View" : true,
"Edit" : false,
"_id" : ObjectId("58eb32fb58bbf720a80daf77")
}
],
"__v" : 0,
"Description" : "Full Control",
"IsActive" : true
}
I want to retrieve only View:true in UIList under UiName:"ManageFacility" 's how to retrieve that.
I tried to get the data following this query but it retrieve all UIList Under Uiname:,View,Edit value.
db.getCollection("manage_roles_news").find(
{ _id:ObjectId("58eb32fb58bbf720a80daf6f")},
{UIList: {$elemMatch: {UiName: "ManageFacility"}}});
How to retrieve that only view in UIlist under Uiname:"ManageFacility"
can anyone tell me
Upvotes: 0
Views: 67
Reputation: 75984
I don't think there is way to project individual fields from positional/elemMatch
projection. It always resolves to array element.
You can try below aggregation to project field. The below query uses $filter operator to find the matching array values which is piped to $arrayAtElem to return the first element (0)
and pass the matching document to $let operator and followed by picking the View
property.
db.getCollection("manage_roles_news").aggregate(
{ $match: { _id: ObjectId("58eb32fb58bbf720a80daf6f") } },
{ $project: {
_id:0,
View:
{ $let: {
vars: {
mElement: {
$arrayElemAt: [{
$filter: {
input: "$UIList",
as: "fElement",
cond: {
$eq: ["$$fElement.UiName", "ManageFacility"]
}
}
}, 0]
}
},
in: {$cond:["$$mElement.View", 1, 0]}
}
}
}
})
Upvotes: 1