Reputation: 45
I saw one post where we can use query: db.collection.find({"pc.pcId": "2"})
and get a record based on pcId
.
result:
{
"name" : "user",
"number":"09xxxxxxx21",
"pc" : [{
"pcId" : "1",
"pcName" : "Desktop",
"pcOwner" : "user1"
}, {
"pcId" : "2",
"pcName" : "Laptop",
"pcOwner" : "user1"
}
]}
}
My question is what if I want result like:
{
"pcId" : "2",
"pcName" : "Desktop",
"pcOwner" : "user1"
}
Not complete record only specific piece of result for which I'm running query. any query?
Upvotes: 1
Views: 428
Reputation: 8894
You can achieve this with aggregation. There are several ways
$unwind
to flat the array$match
$replaceRoot
helps to replace the whole document with the objectMongo script is given below
db.collection.aggregate([
{
"$unwind": "$pc"
},
{
$match: {
"pc.pcId": "2"
}
},
{
"$replaceRoot": {
"newRoot": "$pc"
}
}
])
Working Mongo playground
Second way
$filter
to filter the desire output$arrayElemAt
$ifNull
$replaceRoot
helps to replace the whole document with the objectAnd the mongo script is
[
{
$project: {
pc: {
$ifNull: [
{
$arrayElemAt: [
{
$filter: {
input: "$pc",
cond: {
$eq: [
"$$this.pcId",
"1"
]
}
}
},
0
]
},
[]
]
}
}
},
{
"$replaceRoot": {
"newRoot": "$pc"
}
}
]
Working Mongo playground
Upvotes: 0
Reputation: 334
> db.version();
4.2.6
> db.users.find().pretty();
{
"_id" : ObjectId("5f74aebe377e73757bb7cead"),
"name" : "user",
"number" : "09xxxxxxx21",
"pc" : [
{
"pcId" : "1",
"pcName" : "Desktop",
"pcOwner" : "user1"
},
{
"pcId" : "2",
"pcName" : "Laptop",
"pcOwner" : "user1"
}
]
}
> db.users.aggregate([
... {$unwind:"$pc"},
... {$match:{"pc.pcId":"2"}},
... {$project:{
... "_id":0,
... "pc.pcId":1,
... "pc.pcName":1,
... "pc.pcOwner":1}}
... ]).pretty();
{ "pc" : { "pcId" : "2", "pcName" : "Laptop", "pcOwner" : "user1" } }
>
Upvotes: 1