mongodb - 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
.
解决方案
您可以$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)
推荐阅读
- api - graphql api和rest api的区别
- r - predict.rma() 到 metafor 中的复杂新数据(多项式和因子水平)
- javascript - 在屏幕上反应原生点击
- apache-flink - flink中如何指定任务管理器/任务槽的核数
- mysql - MySQL:从另一个调用存储过程,是否可以将变量发送到我正在调用的存储过程?
- google-pay - WEB 上的 GPay 表在计算运费时有时不显示加载
- azure-devops-migration-tools - FieldMergeMap - 将两列合二为一
- javascript - 如何围绕未折叠的文本制作卡片形状?
- javascript - 如何使用此图像上的颜色蒙版简单地替换颜色然后保存?以 RGBA 通道为例
- flutter - 我有一个关于定义在颤动中移动页面的路线的问题