返回mongoDB中基于字段x的第一个字节x按ytypes分组的logging

如果我有以下json结构:

[ { id: 1, type: "Drinks", isActive : "true", location: "QLD" }, { id: 2, type: "Drinks", isActive : "false", location: "NSW" }, { id: 3, type: "Drinks", isActive : "true" location: "QLD" }, { id: 3, type: "Drinks", isActive : "false" location: "QLD" }, { id: 3, type: "Drinks", isActive : "true" location: "QLD" }, { id: 4, type: "Food", isActive : "true" location: "NSW" }, { id: 4, type: "Food", isActive : "false" location: "NSW" } ] 

我感兴趣的回报是:

 [ { id: 1, type: "Drinks", isActive : "true", location: "QLD" }, { id: 2, type: "Drinks", isActive : "false", location: "NSW" }, { id: 3, type: "Drinks", isActive : "true", location: "QLD" }, { id: 4, type: "Food", isActive : "false", location: "NSW" } ] 

换句话说, give me top 1 of each TYPE in each LOCATION sorted by ID descendinggive me top 1 of each TYPE in each LOCATION sorted by ID descending 。 logging可能会重复,因为样本数据集看起来如此基本上我想每个位置的所有独特的types。 这是可以在mongoD中完成的吗?

这很多不相关,但我在我的nodejs应用程序中使用Mongoose与mongoDB进行交互。

汇总框架可以为您提供所需的结果。 您将不得不按以下顺序运行由3个阶段组成的聚合pipe道:

  1. $sort

    • 这个pipe道将允许您先将订单放入pipe道中,以便以后进行分组。 使用ID降序对文档进行sorting。
  2. $group

    • 组pipe道运算符类似于SQL的GROUP BY子句。 在SQL中,除非使用任何聚合函数,否则不能使用GROUP BY 。 同样的,你也必须在MongoDB中使用一个聚合函数。 在这种情况下,您需要按typelocationid键对所有文档进行分组,并使用所需的$first操作符来引入第一个文档(换句话说,订购时为TOP文档)。
  3. $project

    • 此pipe道步骤与SQL中的SELECT类似。 使用此命令重命名字段名称,并从分组字段中select/取消select要返回的字段。 如果为某个字段指定0,则不会将其发送到下一个运算符。

将所有三个pipe道放在一起,可以运行以下聚合pipe道来获得所需的结果:

 var pipeline = [ { "$sort": { "id": -1 } }, { "$group": { "_id": { "type": "$type", "location": "$location", "id": "$id" }, "isActive": { "$first": "$isActive" } } }, { "$project": { "_id": 0, "id": "$_id.id", "isActive": 1, "type": "$_id.type", "location": "$_id.location" } } ] Model.aggregate(pipeline, function(err, result) { if err throw err; console.log(result); }); 

或者使用stream利的API

 Model.aggregate() .sort("-id") .group({ "_id": { "type": "$type", "location": "$location", "id": "$id" }, "isActive": { "$first": "$isActive" } }) .project({ "_id": 0, "id": "$_id.id", "isActive": 1, "type": "$_id.type", "location": "$_id.location" }) .exec(unction(err, result) { if err throw err; console.log(result); }); 

尝试以下查询: –

 db.collname.aggregate( [ { $group: { _id: "$type", id: { $max: "$id" } } } ] 

请参阅文档了解更多信息。