Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams db.test.find({$or:[{category_id:2},{category_id:2}]).sort({createAt:-1}).limit(5); or db.test.find({category_id:{$in:[1,2]}}).sort({createAt:-1}).limit(5); matthPen Mar 28, 2019 at 16:47 @matthPen In this way, it is possible that I get 7 entries from category 1 and 3 entries from category 2. What I want is same number entries from each category. Elect2 Mar 29, 2019 at 0:49 { "$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)
                I can get the right result using this query. But it doesn't use my Index({category_id:1,createAt:-1}), and run very slow(around 2 second on a 1million docs collection). If I use general find().sort().limit(), it will use index and run fast(0.001 second)
– Elect2
                Mar 29, 2019 at 1:51
                $facet aggregation does not use the index. You have to manually concat the arrays using javascript. I have updated my answer
– Ashh
                Mar 29, 2019 at 7:41
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.