MongoDB返回每个字段的lates记录

时间:2015-05-04 09:25:34

标签: mongodb mongodb-query

假设我有这个rooms集合:

{
    room: 'room1',
    owner: 'user1',
    time: 'time1'
},

{
    room: 'room1',
    owner: 'user1',
    time: 'time2'
},

{
    room: 'room2',
    owner: 'user1',
    time: 'time3'
},

{
    room: 'room2',
    owner: 'user1',
    time: 'time4'
},

{
    room: 'room3',
    owner: 'user1',
    time: 'time5'
},

{
    room: 'room3',
    owner: 'user1',
    time: 'time6'
}

在申请表中,我有一系列房间:[room1, room2, room3]

如何按时间检索房间阵列中每个房间的最新记录?例如,查询应该返回:

{
    room: 'room1',
    owner: 'user1',
    time: 'time2'
},

{
    room: 'room2',
    owner: 'user1',
    time: 'time4'
},

{
    room: 'room3',
    owner: 'user1',
    time: 'time6'
}

1 个答案:

答案 0 :(得分:2)

使用mongoDB aggregation pipeline

1>首先符合您的标准。

2 - ;按time排序。

3>按room分组。

4>项目领域

检查以下聚合查询:

db.collectionName.aggregate({
  "$match": {
    "room": {
      "$in": ["room1", "room2", "room3"] //macth criteria
    }
  }
}, {
  "$sort": {
    "time": -1 //sort by time 
  }
}, {
  "$group": {
    "_id": "$room", // group by room 
    "room": {
      "$first": "$room" // used mongo $first method
    },
    "owner": {
      "$first": "$owner"
    },
    "time": {
      "$first": "$time"
    }
  }
}, {
  "$project": { //project all fileds
    "_id": 0,
    "room": "$room",
    "owner": "$owner",
    "time": "$time"
  }
})

如果您的收藏文档数量超过$sort需要时间进行排序和分组,那么请使用$sort而不是db.collectionName.aggregate({ "$match": { "room": { "$in": ["room1", "room2", "room3"] } } }, { "$group": { "_id": "$room", "time": { "$max": "$time" // use $max }, "room": { "$first": "$room" }, "owner": { "$first": "$owner" } } }, { "$project": { "_id": 0, "room": "$room", "owner": "$owner", "time": "$time" } }) ,如下所示:

scikit-learn