如何在MongoDB中将两个顺序查询变成单个查询

时间:2018-10-26 08:45:35

标签: mongodb

我是MongoDB集合,我按一个批次ID存储多个记录。我将批次ID保留为Date()对象的毫秒数。如何在单个MongoDB查询中检索具有最近/最大批次ID的所有记录。

现在,我正在两个顺序查询中检索记录:

  1. 查找最大/最近的批次ID-recentBatchID = db.users.find().sort( { 'batchID': -1 }).limit(1)

  2. 按最大/最近批次ID db.users.find({'batchID':recentBatchID})

  3. 获取记录

我们如何在单个Mongo查询中进行优化?

样本数据:

[{
        "username": "user1",
        "batchID": "00001"
    },
    {
        "username": "user2",
        "batchID": "00001"
    },
    {
        "username": "user3",
        "batchID": "00001"
    },
    {
        "username": "user4",
        "batchID": "00002"
    },
    {
        "username": "user5",
        "batchID": "00002"
    },
    {
        "username": "user6",
        "batchID": "00002"
    },
]

我正在尝试仅获取最大/最近的user4, user5, user6的{​​{1}}。

1 个答案:

答案 0 :(得分:1)

根据新更新,您可以使用聚合,然后:

db.getCollection('tests').aggregate([
  {$group: {
     _id : "$batchID",
     doc : {$push : "$$ROOT"},
   }},
   {$sort : { '_id': -1 }},
   {$limit: 1},
   {$unwind: "$doc"}
])

输出:

/* 1 */
{
    "_id" : "00002",
    "doc" : {
        "_id" : ObjectId("5bd2dcced79cc5d8b1c6296e"),
        "username" : "user4",
        "batchID" : "00002"
    }
}

/* 2 */
{
    "_id" : "00002",
    "doc" : {
        "_id" : ObjectId("5bd2dcd3d79cc5d8b1c6296f"),
        "username" : "user5",
        "batchID" : "00002"
    }
}

/* 3 */
{
    "_id" : "00002",
    "doc" : {
        "_id" : ObjectId("5bd2dcdbd79cc5d8b1c62970"),
        "username" : "user6",
        "batchID" : "00002"
    }
}