首页 > 解决方案 > MongoDB:如何“联合”来自同一集合的结果?

问题描述

查询.1:

db.test.find({category_id:1}).sort({createAt:-1}).limit(5);

查询.2:

db.test.find({category_id:2}).sort({createAt:-1}).limit(5);

我想要的是使用一个查询得到query1+query2的结果,然后将结果按createAt.

标签: mongodbmongodb-queryaggregation-framework

解决方案


您可以$facet在此处使用聚合。

db.test.aggregate([
  { "$facet": {
    "first": [
      { "$match": { "category_id": 1 }},
      { "$sort": { "createAt": -1 }},
      { "$limit": 5 }
    ],
    "second": [
      { "$match": { "category_id": 2 }},
      { "$sort": { "createAt": -1 }},
      { "$limit": 5 }
    ]
  }},
  { "$project": { "data": { "$concatArrays": ["$first", "$second"] }}},
  { "$unwind": "$data" },
  { "$replaceRoot": { "newRoot": "$data" }}
])

更新

使用简单的 javascript

const test1 = await db.test.find({ category_id: 1 }).sort({ createAt: -1 }).limit(5)

const test2 = await db.test.find({ category_id: 1 }).sort({ createAt: -1 }).limit(5)

const test = test1.concat(test2)

console.log(test)

推荐阅读