MongoDB: How to “union all” results from same collection?

╄→гoц情女王★ 提交于 2019-12-24 07:27:22

问题


query.1:

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

query.2:

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

What I want is use one query get results of query1+query2, and then sort the results by createAt.


回答1:


You can use $facet aggregation here.

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" }}
])

Update

Using simple 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)


来源:https://stackoverflow.com/questions/55400979/mongodb-how-to-union-all-results-from-same-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!