0
{
"_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?

TB.M
  • 363
  • 3
  • 8
  • 26
  • 1
    Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](https://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – Bùi Đức Khánh Dec 05 '17 at 05:02
  • Might be but my value is not fixed in every document so i cannot match on the basis of give me those document where value=A. – TB.M Dec 05 '17 at 05:06
  • Your requirement is about to ignore display items of array with blank value right ? – Bùi Đức Khánh Dec 05 '17 at 07:25
  • yes.I am updating my question. – TB.M Dec 05 '17 at 07:27

2 Answers2

1

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', '']}
            }}
        }}
    ])
Bùi Đức Khánh
  • 3,975
  • 6
  • 27
  • 43
0
db.collection.find({
    'data.field.fields': {
        $elemMatch: {
            value: 'A'
        }
    }
}, {
    'data.field.fields.$': 1
})
tomtastico
  • 6,136
  • 2
  • 23
  • 28
Rubin Porwal
  • 3,736
  • 1
  • 23
  • 26
  • its matching perfectly only i want to see only "value" : "A" key value but with this other key values are also coming which is there in array. – TB.M Dec 05 '17 at 07:03