我正在使用流星,并且自3天以来难以解决此问题。我搜索了stackoverflow,但答案似乎无法满足我的需求。我有一个销售表,上面有以下数据。
{
"_id" : 1,
"table" : "Table no 2",
"name" : "Hot Coffee",
"quantity" : 2,
"price" : "$10",
"seller" : "User",
"createdAt" : ISODate("2016-01-06T12:57:17.152Z")
},
{
"_id" : 2,
"table" : "Table no 3A",
"name" : "Hot Coffee",
"quantity" : 1,
"price" : "$10",
"seller" : "User",
"createdAt" : ISODate("2016-02-01T12:58:17.152Z")
},
{
"_id" : 3,
"table" : "Table no 3A",
"name" : "Pizza",
"quantity" : 2,
"price" : "$50",
"seller" : "User",
"createdAt" : ISODate("2016-01-06T12:58:17.152Z")
},
{
"_id" : 4,
"table" : "2A",
"name" : "Pizza",
"quantity" : 5,
"price" : "$50",
"seller" : "User",
"createdAt" : ISODate("2016-02-02T11:55:17.152Z")
},
我期望添加所有数量的独特表名称
{
"name":"Hot Coffee",
"quantity": 3
},
{
"name":"Pizza",
"quantity": 7
}
我尝试了独特的功能,但似乎只显示一个结果。
为此,请使用聚合框架,但是由于Meteor还不支持聚合,因此您需要安装聚合框架程序包-它不会起到任何作用,只是为您包装了一些Mongo方法。
只需添加流星meteorhacks:aggregate
,您就可以开展业务。这将为Meteor添加适当的聚合支持。
现在,您将需要此管道来获得所需的结果。在mongo shell中,运行以下命令:
var pipeline = [
{
"$group": {
"_id": "$name",
"quantity": { "$sum": "$quantity" }
}
},
{
"$project": {
"name": "$_id", "_id": 0, "quantity": 1
}
}
];
db.sales.aggregate(pipeline);
样本输出
{
"result" : [
{
"quantity" : 7,
"name" : "Pizza"
},
{
"quantity" : 3,
"name" : "Hot Coffee"
}
],
"ok" : 1
}
聚合操作的作用是使用$group
流水线步骤将所有文档按name
字段分组,对于每个不同的组,您可以使用累加器运算符$sum
对每个组的数字字段数量进行累加总数量。下一个管道$project
将把前一个管道流文档中的字段重塑为所需的结构。
在Meteor中,您可以Sales
使用以下模式将这些结果发布到客户端上的集合中,前提是您已将汇总包添加到流星应用程序中:
Meteor.publish('getDistinctSalesWithTotalQuantity', function (opts) {
var initializing = 1;
function run(action) {
// Define the aggregation pipeline ( aggregate(pipeline) )
var pipeline = [
{
"$group": {
"_id": "$name",
"quantity": { "$sum": "$quantity" }
}
},
{
"$project": {
"name": "$_id", "_id": 0, "quantity": 1
}
}
];
Sales.aggregate(pipeline).forEach(function(e){
this[action]('distinct-sales', e.name, e)
this.ready()
});
};
// Run the aggregation initially to add some data to your aggregation collection
run('added');
// Track any changes on the collection we are going to use for aggregation
var handle = Sales.find({}).observeChanges({
added(id) {
// observeChanges only returns after the initial `added` callbacks
// have run. Until then, we don't want to send a lot of
// `self.changed()` messages - hence tracking the
// `initializing` state.
if (initializing && initializing--) run('changed');
},
removed(id) {
run('changed');
},
changed(id) {
run('changed');
},
error(err) {
throw new Meteor.Error('Aaaaaaaaah! Grats! You broke it!', err.message)
}
});
// Stop observing the cursor when client unsubs.
// Stopping a subscription automatically takes
// care of sending the client any removed messages.
this.onStop(function () {
handle.stop();
});
});
以上内容会观察到更改,并在必要时重新运行聚合。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句