Search multiple _id created by the combination of two fields

Hey I have groups with 2 properties which together create 1 unique ID. We can’t have the same a and b repeated.

_id: {{ a: 1,  b: 3 }}
_id: {{ a: 2,  b: 2 }}
_id: {{ a: 1,  b: 2 }}

I have two problems

  1. The order of the properties shouldn’t be important. {a:1, b:2} === {b:2,a:1}
  2. I need to search for multiple object in the same query as if I were using the $in operator for 1 property IDs.

Something like this

db.inventory.find( { $in: [ {_id: {a: 1, b: 1}, {a: 1,b: 1} }] } )

What is the best approach to accomplish this?

The above will be hard to enforce as in most drivers and languages the 2 objects differs. Your best bet is to make sure you do your inserts with an API. You may use triggers or change stream to make sure you are notified of the invalid inserts.

Try the following

 { _id : { $in: [ {a: 1, b: 1}, {a: 2,b: 3} ] }

rather than

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.