嵌套对象

时间:2016-01-11 14:59:43

标签: javascript mongodb meteor

我正在尝试创建一个仪表板,在其中显示应用程序中的订单数据摘要。在这种情况下,我只想在Orders集合中计算给定类别中的项目数。到目前为止我的代码看起来像这样:

收集数据

{
    "_id" : "a6wHiXxyM5DwSAsfq",
    "orderNumber" : 1234,
    "createdAt" : "11/01/2016, 14:43:49",
    "productsInOrder" : [
        {
            "category" : "ambient",
            "item" : 50818,
            "desc" : "Tasty Rubber Chicken",
            "quantity" : "44",
            "price" : "0.92",
            "lineprice" : "40.48",
            "_id" : "FFNxG8vujs6NGN69r"
        },
        {
            "category" : "frozen",
            "item" : 71390,
            "desc" : "Generic Granite Fish",
            "quantity" : "11",
            "price" : "1.00",
            "lineprice" : "11.00",
            "_id" : "LcRtpyLxkWyh39kkB"
        }
    ]
}
{
    "_id" : "PdpywXCvfew7qojmA",
    "orderNumber" : 1234,
    "createdAt" : "11/01/2016, 14:44:15",
    "productsInOrder" : [
        {
            "category" : "frozen",
            "item" : 71390,
            "desc" : "Generic Granite Fish",
            "quantity" : "44",
            "price" : "1.00",
            "lineprice" : "44.00",
            "_id" : "dAscx4R8pcBgbzoZs"
        },
        {
            "category" : "frozen",
            "item" : 66940,
            "desc" : "Gorgeous Granite Bike",
            "quantity" : "55",
            "price" : "4.21",
            "lineprice" : "231.55",
            "_id" : "xm3mFRmPmmdPxjfP9"
        },
        {
            "category" : "frozen",
            "item" : 96029,
            "desc" : "Gorgeous Plastic Fish",
            "quantity" : "1234",
            "price" : "4.39",
            "lineprice" : "5417.26",
            "_id" : "7u7SHnpTf7PWcrhGA"
        }
    ]
}
{
    "_id" : "xcHZ25qwvyDpDJtAZ",
    "orderNumber" : 1234,
    "createdAt" : "11/01/2016, 14:44:47",
    "productsInOrder" : [
        {
            "category" : "frozen",
            "item" : 31104,
            "desc" : "Handcrafted Rubber Keyboard",
            "quantity" : "11",
            "price" : "4.78",
            "lineprice" : "52.58",
            "_id" : "LMMwbKFEgnCbgCt9c"
        },
        {
            "category" : "frozen",
            "item" : 77832,
            "desc" : "Practical Rubber Shirt",
            "quantity" : "21",
            "price" : "0.62",
            "lineprice" : "13.02",
            "_id" : "63otkkXWGrTJkwEgX"
        },
        {
            "category" : "frozen",
            "item" : 66940,
            "desc" : "Gorgeous Granite Bike",
            "quantity" : "111",
            "price" : "4.21",
            "lineprice" : "467.31",
            "_id" : "rbPSujey8CFeMPjza"
        }
    ]
}

JS

到目前为止,我已经尝试过:

Orders.find({ 'productsInOrder': ['ambient']}).count();
Orders.find({ productsInOrder: { category: 'ambient' }}).count();
Orders.find({ productsInOrder: { $all: [ 'frozen' ] }}).count();

当数据以这种方式嵌套时,我很难理解Mongo查询。请帮助我指出正确的方向?非常感谢提前。

*解决方案*

由于以下贡献,我已经完成了预期的结果。为了完成这项工作,我在服务器上创建了一个方法,因为无法使用现有集合在客户端上运行查询。这样做如下:

Meteor.methods({
  'byCategory': function() {
    var result = Orders.aggregate([
        { "$unwind": "$productsInOrder" },
        {
            "$group": {
                "_id": null,
                "ambient_count": {
                    "$sum": {
                        "$cond": [ { "$eq": [ "$productsInOrder.category", "ambient" ] }, 1, 0 ]
                    }
                },
                "frozen_count": {
                    "$sum": {
                        "$cond": [ { "$eq": [ "$productsInOrder.category", "frozen" ] }, 1, 0 ]
                    }
                },
                "other_category_count": {
                    "$sum": {
                        "$cond": [ { "$eq": [ "$productsInOrder.category", "other_category" ] }, 1, 0 ]
                    }
                }
            }
        }
    ]);

    return result;
  }
})

然后在客户端上:

Meteor.call('byCategory', function( error, result ) {
  if( error ) {
    console.log( error.reason );
  } else {
    console.log( result[0].ambient_count );
    console.log( result[0].frozen_count );
    etc....
  }
});

感谢@chridam和@Brett。

2 个答案:

答案 0 :(得分:3)

另一种方法是使用 aggregation framework 。考虑以下聚合管道,作为聚合管道的第一阶段, $unwind 运算符对要为每个输入文档输出的productsInOrder数组进行非规范化,n文档其中n是数组元素的数量。下一个管道阶段有 $group 运算符,该运算符将所有文档分组到一个文档中,并在 $sum的帮助下存储每个类别的计数 $cond 运营商。

在Meteor中,您可以使用 meteorhacks:aggregate package 来实施聚合:

使用

添加到您的应用中
meteor add meteorhacks:aggregate

请注意,这仅适用于服务器端,并且没有内置的支持或反应性。然后只需使用 .aggregate 功能,如下所示。

var coll = new Mongo.Collection('orders');
var pipeline = [
    { "$unwind": "$productsInOrder" },
    {
        "$group": {
            "_id": null, 
            "ambient_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$productsInOrder.category", "ambient" ] }, 1, 0 ]
                }
            },
            "frozen_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$productsInOrder.category", "frozen" ] }, 1, 0 ]
                }
            },
            "other_category_count": {
                "$sum": {
                    "$cond": [ { "$eq": [ "$productsInOrder.category", "other_category" ] }, 1, 0 ]
                }
            }
        }
    }       
];
var result = coll.aggregate(pipeline);

使用示例数据在mongo shell中运行相同的管道将产生:

{
    "result" : [ 
        {
            "_id" : null,
            "ambient_count" : 1,
            "frozen_count" : 7,
            "other_category_count" : 0
        }
    ],
    "ok" : 1
}

您可以访问本机mongo集合并将聚合结果发布到客户端的orders集合:

Meteor.publish('categoryCounts', function() {  
    var self = this,
        db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;

    orders = db.collection("orders").aggregate(pipeline, // Need to wrap the callback so it gets called in a Fiber.
        Meteor.bindEnvironment(
            function(err, result) {
                // Add each of the results to the subscription.
                _.each(result, function(e) {
                    self.added("orders", e._id, e);
                });
                self.ready();
            },
            function(error) {
                Meteor._debug( "Error doing aggregation: " + error);
            }
        )
    );
});

答案 1 :(得分:2)

如果您不想在Meteor中执行此操作,则需要使用mongo聚合。 Minimongo不包含聚合,所以你需要这个包来完成它:

https://docs.mongodb.org/manual/core/aggregation-introduction/

我只在mongo本身测试过这个,所以你必须使它适应聚合包的方式:

db.orders.aggregate([
    {
        $unwind: "$productsInOrder"
    }, 
    {
        $match: {
            "productsInOrder.category": "frozen"
        }
    },
    {
        $group: {
            _id: null, 
            count: {
                $sum: 1
            }
         }
     }
]);

第一部分是展开集合。它基本上会产生一个"命令" $ productsInOrder的每个实例的条目。一旦你把阵列弄平了,我们就匹配你关心的类别;在这种情况下,"冷冻"类别。接下来我们将其分组,以便我们可以计算返回的文档数量。 $ group只是构造将从查询输出的最终对象。您可以将其修改为您想要的任何内容,或者您​​可以按productsInOrder.category进行分组,甚至不会将$ match匹配为"冻结"。