如何在MongoDB中访问嵌套文档中的值?

如何在MongoDB中访问嵌套文档中的值?,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我试图找出xbox、ps4和wii的平均销量。我正在处理嵌套文档,我尝试使用db.console.find({“market.type”:“sell”})访问type以过滤“sell”;但我最终也得到了“在线”类型的值 Document 1: _id:("111111111111111111111111") market:Array 0:Object type:"sell" console:"Xbox" amount:399 1:Object

我试图找出xbox、ps4和wii的平均销量。我正在处理嵌套文档,我尝试使用db.console.find({“market.type”:“sell”})访问type以过滤“sell”;但我最终也得到了“在线”类型的值

Document 1:
_id:("111111111111111111111111")
market:Array
   0:Object
      type:"sell"
      console:"Xbox"
      amount:399
   1:Object
      type:"online"
      console:"PS4"
      amount:359
   2:Object
      type:"sell"
      console:"xbox"
      amount:349

由于您需要从文档中筛选子文档,因此仅使用
find
无法筛选子文档

您必须使用聚合管道,如下所示:

    > db.st9.aggregate([
    {
        $unwind:"$market"
    }, 
    {
        $match: {"market.type":"sell"}
    }, 
    {
        $group: {_id:"$market.console", "avg": {$avg:"$market.amount"}, "count": {$sum:1}, "totalSum": {$sum: "$market.amount"} }
    } 
])
输出:

{ "_id" : "PS4", "avg" : 300, "count" : 1, "totalSum" : 300 }
{ "_id" : "Xbox", "avg" : 359, "count" : 3, "totalSum" : 1077 }
>
有关聚合管道的更多参考,请查看以下官方mongo db文档:


  • 由于您需要从文档中筛选子文档,因此仅使用
    find
    无法筛选子文档

    您必须使用聚合管道,如下所示:

        > db.st9.aggregate([
        {
            $unwind:"$market"
        }, 
        {
            $match: {"market.type":"sell"}
        }, 
        {
            $group: {_id:"$market.console", "avg": {$avg:"$market.amount"}, "count": {$sum:1}, "totalSum": {$sum: "$market.amount"} }
        } 
    ])
    
    输出:

    { "_id" : "PS4", "avg" : 300, "count" : 1, "totalSum" : 300 }
    { "_id" : "Xbox", "avg" : 359, "count" : 3, "totalSum" : 1077 }
    >
    
    有关聚合管道的更多参考,请查看以下官方mongo db文档:


  • 为此,您必须使用聚合管道,而不仅仅是查找。有关更多信息,请查看MongoDB文档:您必须为此使用聚合管道,而不仅仅是查找。有关更多信息,请查看MongoDB文档: