在Meteor.js中选择具有唯一字段组合的记录

时间:2014-01-13 14:57:44

标签: javascript node.js mongodb meteor

在Meteor.js中,我们如何选择独特的字段组合?例如,如果我们有:

type    color    owner
----    -----    -----
animal  red      paul
animal  red      jack
animal  blue     paul
food    blue    jack

如何获得以下结果集:

type    color 
----    ----- 
animal  red
animal  blue
food    blue

我正在使用meteor-smart-collections 0.4.0和Meteor 0.7.0.1

2 个答案:

答案 0 :(得分:0)

如果您准备好fetch(),可以使用下划线来轻松完成此操作,这可能取决于您获得的文档数量:

_.uniq(yourCollection.find({}, {fields: {type: 1, color: 1, _id: 0}}).fetch(), function(item) { return item.type+item.color; });

唯一的警告是您为了进行比较而连接字符串,因此如果有{type: 'foo', color: 'bar'}{type: 'foob', color: 'ar'}这样的对可能会失败。在你给出的例子中,这似乎不太可能,但是如果你担心它是一个问题,你只需要改变迭代器函数的结构来做一些比连接更有想象力的事情。这两个领域。它需要返回一个原语,但如果你返回一个对象或一个数组,我认为它不会起作用。

答案 1 :(得分:0)

我认为Meteor的Minimongo驱动程序尚未包含聚合框架的帮助程序,但至少有一个问题存在suggestions on how to call the underlying MongoDB aggregate command

假设您的数据如下:

db.things.insert([
    { type: 'animal', color: 'red',  owner: 'paul'},
    { type: 'animal', color: 'red',  owner: 'jack'},
    { type: 'animal', color: 'blue', owner: 'paul'},
    { type: 'food',   color: 'blue', owner: 'jack'}
])

您可以使用MongoDB的Aggregation Framework$group operator在服务器端进行此分组:

db.things.aggregate(
    { $group: {
        _id: { type: "$type", color: "$color" }
    }}
)

结果如下:

{
    "result" : [
        {
            "_id" : {
                "type" : "food",
                "color" : "blue"
            }
        },
        {
            "_id" : {
                "type" : "animal",
                "color" : "blue"
            }
        },
        {
            "_id" : {
                "type" : "animal",
                "color" : "red"
            }
        }
    ],
    "ok" : 1
}
相关问题