2

There are some data in my mongodb collection like this :

{"_id":{"$oid":"60603f0075ee1d1cdcd95d1a"},
"store_id":{"$oid":"60603dd675ee1d1cdcd95d18"},
"product_id":{"$oid":"6062f6973f24de12f0264013"}}

I wanna pass query , my query is list of store_id if all of element of list is exist in database return something like true else if even one of the element not match in database return something like false...

I can check one by one and use findOne ,but i don't wanna to check one by one!

Update: I can do this by for and findOne but i don't wanna send a lot of query to db !

milad_vayani
  • 398
  • 1
  • 4
  • 14

1 Answers1

1

I could only come up with this: pass the list of store_ids and number of store_ids. Filter for items by store_id and count haw many unique store_ids there, then compare the number with the number of store_ids you passed in the query. You can express this using aggregation.

And if you use aggregation, you always get document (object) back from MongoDB: {'filedA': false}, so you can't get just false1.

storeIds= [123, 1234, 12345];
numStoreIds = storeIds.length;

pipeline=
[{$match: {
  orderId: {$in: storeIds}
}}, {$group: {
  _id: "$storeId"
}}, {$count: 'num'}, {$project: {
  result: {
    $cond: [ { $eq: [ "$num", numStoreIds ] }, true, false]
  }
}}]

db.collection.aggregate(pipeline)

>
{ "result" : true }
Katya Kamenieva
  • 316
  • 1
  • 5