Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB filter array element in a nested object

Tags:

mongodb

I have a document as follows:

{
    "_id" : ObjectId("56423b2558cb340599108b35"),
    "test" : {
        "source" : [
            {
                "member" : "abc"
            },
            {
                "member" : "xyz"
            }
        ]
    }
}

I want to filter on the array element xyz, and I am trying the following query:

db.coll.find({ "test.source.member" : "xyz" }, { "test.source.$.member" : true }).pretty()

Apparently it used to work on 2.4, on 2.6 it does not work,

On 2.4 it returned the "xyz", whereas on 2.6 it returns "abc" i.e. the first element. Is there a way to filter "abc" because eventually i want to update. BTW, i also tried with $elemMatch and it seems to give the same output "abc".

Thanks.

like image 473
user2766839 Avatar asked Sep 15 '26 09:09

user2766839


1 Answers

According to the Docs, if you are running 2.6, this should give you the correct output:

db.coll.find({ "test.source.member" : "xyz"}, { "test.source.$" : 1}).pretty()

You could extract the member by doing this:

var member = db.coll.find(
                 { "test.source.member" : "xyz"},
                 { "test.source.$" : 1}
                 ).test.source[0].member;

The value of member would be:

xyz
like image 156
Abdullah Rasheed Avatar answered Sep 19 '26 01:09

Abdullah Rasheed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!