流星查询具有唯一字段的所有文档
meteor query for all documents with unique field
我想完全按照 SO question 的目的进行操作,但是在服务器端使用 Meteor:
How do I retrieve all of the documents which HAVE a unique value of a
field?
> db.foo.insert([{age: 21, name: 'bob'}, {age: 21, name: 'sally'}, {age: 30, name: 'Jim'}])
> db.foo.count()
3
> db.foo.aggregate({ $group: { _id: '$age', name: { $max: '$name' } } }).result
[
{
"_id" : 30,
"name" : "Jim"
},
{
"_id" : 21,
"name" : "sally"
}
]
我的理解是 aggregate
不适用于 Meteor。如果那是正确的,我怎样才能实现上述目标?事后对查询执行 post 过滤不是理想的解决方案,因为我想使用 limit
。只要我可以使用 limit
.
,我也很乐意以其他方式获取具有唯一字段的文档
有一个通用设置可用于访问底层驱动程序集合对象,因此 .aggregate()
无需安装任何其他插件。
基本流程是这样的:
FooAges = new Meteor.Collection("fooAges");
Meteor.publish("fooAgeQuery", function(args) {
var sub = this;
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var pipeline = [
{ "$group": {
"_id": "$age",
"name": { "$max": "$name" }
}}
];
db.collection("foo").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) {
// Generate a random disposable id for aggregated documents
sub.added("fooAges", Random.id(), {
"age": e._id,
"name": e.name
});
});
sub.ready();
},
function(error) {
Meteor._debug( "Error doing aggregation: " + error);
}
)
);
});
因此,您为聚合的输出定义一个集合,然后在这样的例程中发布您也将在客户端中订阅的服务。
在此内部,聚合是 运行 并填充到另一个集合中(逻辑上它实际上不写任何东西)。因此,您然后在具有相同定义的客户端上使用该集合,所有聚合结果都将返回。
实际上,如果您需要进一步参考,我在 , as well as usage of the meteor hacks aggregate package on 中也有类似流程的完整工作示例应用程序。
我想完全按照 SO question 的目的进行操作,但是在服务器端使用 Meteor:
How do I retrieve all of the documents which HAVE a unique value of a field?
> db.foo.insert([{age: 21, name: 'bob'}, {age: 21, name: 'sally'}, {age: 30, name: 'Jim'}])
> db.foo.count()
3
> db.foo.aggregate({ $group: { _id: '$age', name: { $max: '$name' } } }).result
[
{
"_id" : 30,
"name" : "Jim"
},
{
"_id" : 21,
"name" : "sally"
}
]
我的理解是 aggregate
不适用于 Meteor。如果那是正确的,我怎样才能实现上述目标?事后对查询执行 post 过滤不是理想的解决方案,因为我想使用 limit
。只要我可以使用 limit
.
有一个通用设置可用于访问底层驱动程序集合对象,因此 .aggregate()
无需安装任何其他插件。
基本流程是这样的:
FooAges = new Meteor.Collection("fooAges");
Meteor.publish("fooAgeQuery", function(args) {
var sub = this;
var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var pipeline = [
{ "$group": {
"_id": "$age",
"name": { "$max": "$name" }
}}
];
db.collection("foo").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) {
// Generate a random disposable id for aggregated documents
sub.added("fooAges", Random.id(), {
"age": e._id,
"name": e.name
});
});
sub.ready();
},
function(error) {
Meteor._debug( "Error doing aggregation: " + error);
}
)
);
});
因此,您为聚合的输出定义一个集合,然后在这样的例程中发布您也将在客户端中订阅的服务。
在此内部,聚合是 运行 并填充到另一个集合中(逻辑上它实际上不写任何东西)。因此,您然后在具有相同定义的客户端上使用该集合,所有聚合结果都将返回。
实际上,如果您需要进一步参考,我在