0

I have the following document

db.c.save({a:[{u:3},{u:6},{u:123}]});

I want to fetch matching elements from the array. So I use the following query to do it.

db.c.find({'a.u':{$in:[3,123]}},{'a.$':1});

This gives me { "a" : [ { "u" : 3 } ] } but I guess it should return { "a" : [ { "u" : 3 }, { "u" : 123 } ] }

Any suggestions?

1 Answer 1

1

Unfortunately, the $ positional operator only returns the first match so you can't use it to do what you are trying to do.

However, you can use either aggregation or map-reduce. The following code does what you want using the aggregation framework :

db.c.aggregate([
  { $unwind : "$a"},
  { $match  : { "a.u" : {$in :[3,123]} } },
  { $group  : {_id : "$_id",a : { $push : "$a" } } }
])
Sign up to request clarification or add additional context in comments.

Comments

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.