Searching for elements in array and return matching elements in mongodb

后端 未结 1 1563
盖世英雄少女心
盖世英雄少女心 2021-01-26 06:30

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 q

1条回答
  •  清酒与你
    2021-01-26 07:11

    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" } } }
    ])
    

    0 讨论(0)
提交回复
热议问题