首页 > 解决方案 > MONGOOSE - 仅返回匹配数组过滤器的对象

问题描述

我在 mongoDB 中有一个这样的数据结构

{_id:ObjectId(''),
"awards" : [
               {
                       "award" : "Ballon d'Or",
                       "numberOfTimes" : 6
               },
               {
                       "award" : "Golden Boot",
                       "numberOfTimes" : 6
               },
               {
                       "award" : "FIFA World Player of the Year",
                       "numberOfTimes" : 1
               }
       ],
push:true
}

我目前正在使用这个月光过滤器{'awards.award':"Ballon d'Or"}

我只想在奖项数组中返回与金球奖相匹配的对象

所以输出看起来像这样

{_id:ObjectId(''),
"awards" : [
               {
                       "award" : "Ballon d'Or",
                       "numberOfTimes" : 6
               }
       ],
push:true
}

谢谢

标签: node.jsmongodbmongoose

解决方案


您可以projection operator '$'为此使用:

你可以试试:

db.collection.find({'awards.award':"Ballon d'Or"}, {'awards.$' : 1})

awards.$:1只会从奖项数组中返回匹配的对象。

注意: $(projection)运算符仅返回数组的第一个匹配元素

备用:

如果你想要所有匹配的元素,你可以使用聚合管道。您将需要首先展开奖励数组,应用过滤器以仅获得所需的结果,然后再次将它们分组以获取数组。

试试这个聚合管道:

db.collection.aggregate([
  {
    "$unwind": "$awards"
  },
  {
    $match: {
      "awards.award": "Ballon d'Or"
    }
  },
  {
    $group: {
      _id: "$_id",
      push: {
        $first: "$push"
      },
      awards: {
        $push: "$awards"
      }
    }
  }
])

看看这个MongoDB Playground来玩聚合管道。


推荐阅读