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.
解决方案
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)