Reputation: 363
{
"_id" : ObjectId("55caf0298c1c44740469306c"),
"data" : {
"field" : {
"fields" : [
{
"name" : "demo",
"type" : "data",
"value" : "A"
}
]
}
}
}
I want Only those Array element should come where value=A, rest is blank so it should not show.
Desire Output:
{
"_id" : ObjectId("55caef098c1c447404693064"),
"data" : {
"field" : {
"fields" : [
{
"value" : "A"
}
]
}
}
}
And also after finding all values in document I want to modify those values.
Note: value=A is not always first element ,it can be 2nd 3rd element.And in each document "value" : "A" is not not fixed it can be different like "value" : "B", only i want those document where value key is having value and where its blank it should not show.
Query:
db.getCollection('collection').aggregate([
{$match: {'data.field.fields.name': 'demo'}},
{ "$project": {
"_id": 0,
"value": { "$arrayElemAt": ["$data.field.fields.value", 0] }
}}
])
Now i want to update the value .How can I update?
Upvotes: 0
Views: 230
Reputation: 3845
db.collection.find({
'data.field.fields': {
$elemMatch: {
value: 'A'
}
}
}, {
'data.field.fields.$': 1
})
Upvotes: 0
Reputation: 4518
If your mongodb version higher than 3.2 you can using $filter for projection https://docs.mongodb.com/master/reference/operator/aggregation/filter/#exp._S_filter
Hope this help
db.yourtable.aggregate([
{$project: {
"data.field.fields": {$filter: {
input: '$data.field.fields',
as: 'fields',
cond: {$ne: ['$$fields.value', '']}
}}
}}
])
Upvotes: 1