简体   繁体   中英

Search documents with multiple arrays to check if given values exists in each array in mongoDB

I have a document like

  Doc1 - {
   'category' : [c1,c2]
   'location': [l1,l2]
 }

  Doc2 - {
   'category' : [c1]
   'location': [l1]
 }

Doc2 array elements are subelements of Doc1 array.

Can I use mongo aggregation query to mark them as duplicate or should i use full text search on each array by unwinding them ?

I am open to changing the structure of document instead of array if it can meet my business requirement.

I need to restrict use from entering document with similar array inputs like above.

Business reason - User will provide one of the array value for each array key, and during evaluation, the system should have only one document matching or none.

You can $unwind by 'category' then 'location' and then 'groupBy' category and location. In this way you can 'push' the _id that match the group.

At the end you will have an array of 'category+location' and inside this item you will have a list of all _id that match. At least you have one element. Or maybe 2 elements if duplicate are found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM