1

Let's say I have a database of product inventory stating the status of each product instance.

[
  { prod: A, location: 1, status: 1 },
  { prod: A, location: 1, status: 2 },
  { prod: A, location: 2, status: 1 },
  { prod: A, location: 3, status: 1 },
  { prod: B, location: 2, status: 2 },
  { prod: B, location: 1, status: 1 },
  { prod: B, location: 1, status: 2 },
  { prod: B, location: 1, status: 2 },
  { prod: C, location: 1, status: 1 }
]

And we have some dynamic query pair like

[A: 2, B: 4]

where the digit is the result limit for the corresponding product. (meaning we want two As and four Bs) (and of course there can be Cs and Ds etc.)

Now I know in aggregation we can match status=1 and prod %in% [A,B].
And we can put a overall $limit on the whole query result like filtering 10 entries only.
And $slice is not useful too since it cannot take multiple parameters.

So, must I do multiple queries or is there an efficient way to do this in one aggregation?

(I have searched a lot and seems we only have solutions for top N results for every group.
example: Multiple limit condition in mongodb )

EDIT:

To clarify, basically I want different limits for different products.
This is what I can do, using a for-loop to do multiple queries.
But is there a way to do it in one aggregation without looping?

q = {A:2, B:4};
allResult = [];
Object.keys(q).forEach(k => {
    result = db.find({prod:k}).limit(q[k]).exec();  //find for one prod
    allResult = allResult.concat(result);
});

Expected output:
[
  { prod: A, location: 1, status: 1 },
  { prod: A, location: 1, status: 2 },
  { prod: B, location: 2, status: 2 },
  { prod: B, location: 1, status: 1 },
  { prod: B, location: 1, status: 2 },
  { prod: B, location: 1, status: 2 }
]

0 Answers0