3

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.

1
  • The posted 'code' is definitely not C, so please remove the 'c' tag Commented Nov 13, 2015 at 8:29

1 Answer 1

5

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

8 Comments

Same as before. does not show the correctly filtered item.
@user2766839 when you run db.version() what does it output in mongo shell?
@inspired, shouldn't it be { "test.source.$" : 1 } instead of { "test.source.$.member" : 1 } in order to get only the first element from the source array that has member "xyz"? If no, can you please explain why? Thanks.
I tried inserting a fresh query and then the filtering works. However after upgrade the filtering does not seem to work in other records. Currently investigating that.
@LisaGagarina, you are right test.source.$ is correct, but when i tested test.source.$.member I didn't get an error. Thanks, I'll update it
|

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.