我正在处理以下文件
{
"_id" : 12,
"firstName" : "wer",
"People" : [
{
"uuid" : "123",
"name" : "sugun",
"person" : [
{
"uuid" : "add32",
"name" : "ssss"
},
{
"uuid" : "fdg456",
"name" : "gfg"
}
]
},
{
"uuid" : "222",
"name" : "kiran"
}
]
}
我希望我的输出如下
{
"_id" : 456,
"People" : [
{
"uuid" : "123",
"name" : "sugun",
"person" : [
{
"uuid" : "add32",
"name" : "ssss"
}
]
}
]
}
当iam在mongo shell中使用以下命令时,它会提供我所需的输出
db.people.aggregate([
{$match: {_id: 12}},
{$unwind: "$People"},
{$unwind: "$People.person"},
{$match: {"People.uuid": "123", "People.person.uuid" : "add32"}}
])
但是当我在我的流星应用程序中使用相同的时候聚合不起作用...... 所以我可以使用find或findOne方法做同样的事情............. 或者如果有可能在我的流星应用程序中使用聚合函数....
答案 0 :(得分:6)
我使用了meteorhacks:聚合包。它仅适用于服务器端。
meteor add meteorhacks:aggregate
MyCollection.aggregate({
$match: {
propertyToQuery: 'valueForProperty'
}, {
$group: {
_id: '$propertyToGroupBy',
result: { $operation: '$propertyToPerformOperationOn' }
}
});
https://github.com/meteorhacks/meteor-aggregate https://themeteorchef.com/snippets/aggregations-in-mongodb/
答案 1 :(得分:2)
以下是我手动尝试并为我工作的内容:
var rawUsers = Meteor.users.rawCollection();
var aggregateQuery = Meteor.wrapAsync(rawUsers.aggregate, rawUsers);
var pipeline = [
{$match: {}},
{$project: {username: 1, profile: 1}}
];
var result = aggregateQuery(pipeline);
return result;
答案 2 :(得分:1)
您需要添加一个包以展示aggregate
功能:
meteor add monbro:mongodb-mapreduce-aggregation
然后你可以使用正常的代码:
var MyCollection = new Mongo.Collection('metrics');
var pipeline = [
{$group: {_id: null, resTime: {$sum: "$resTime"}}}
];
var result = MyCollection.aggregate(pipeline);
只需注意几点,这在服务器端最有效。对于在客户端使用它的文档,需要包的一个分支,检查包的文档:https://atmospherejs.com/monbro/mongodb-mapreduce-aggregation
答案 3 :(得分:0)
通过使用rawCollection
,您可以传递与mongo shell相同的管道。
无需安装第三方程序包。
const stats = await MyCollection.rawCollection()
.aggregate([
{$match: {_id: 12}},
{$unwind: "$People"},
{$unwind: "$People.person"},
{$match: {"People.uuid": "123", "People.person.uuid" : "add32"}}
])
.toArray();