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?

4
  • 1
    Possible duplicate of Retrieve only the queried element in an object array in MongoDB collection Commented Dec 5, 2017 at 5: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. Commented Dec 5, 2017 at 5:06
  • Your requirement is about to ignore display items of array with blank value right ? Commented Dec 5, 2017 at 7:25
  • yes.I am updating my question. Commented Dec 5, 2017 at 7:27

2 Answers 2

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', '']}
            }}
        }}
    ])
Sign up to request clarification or add additional context in comments.

Comments

0
db.collection.find({
    'data.field.fields': {
        $elemMatch: {
            value: 'A'
        }
    }
}, {
    'data.field.fields.$': 1
})

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.