Reputation: 65
I have a mongo collection named 'demo', which is having the following structure:
{
"_id" : ObjectId("59d600182c44a11cec2b9ac5"),
"User_ID" : "user-12",
"Status" : {
"User_Status" : "Registered",
"Location" : "USA"
}
}
I have used the following mongo query to fetch data:
db.demo.find({},
{
User_ID:1,
"Status.User_Status":1
})
The output of above query is:
{
"_id" : ObjectId("59d600182c44a11cec2b9ac5"),
"User_ID" : "user-12",
"Status" : {
"User_Status" : "Registered"
}
}
But my requirement is to achieve the following output:
{
"_id" : ObjectId("59d600182c44a11cec2b9ac5"),
"User_ID" : "user-12",
"User_Status" : "Registered"
}
Is there any way to disable to parent document (Status) and get only result for sub-document "User_Status". Thanks for any help.
Upvotes: 2
Views: 209
Reputation: 3354
Use aggregate instead find and project operator.
db.demo.aggregate( {$project: {User_Status:'$Status.User_Status', User_ID:'$User_ID'}} );
Upvotes: 2
Reputation: 348
Yes, you can use aggregate
with project
instead of find
Use the below command get your desired result :
db.dummy.aggregate(
{
$project:
{
User_ID:1,
User_Status:"$Status.User_Status"
}
})
Upvotes: 2