I am looking for a way to do exclusive OR on MongoDB.
For instance, $or
works as expected:
> db.mycollection.find({ '$or': [ { 'a': 1 }, { 'b': 1 } ] })
But I would need to find records where a
is 1 or b
is 1, but not both of them. Something like this:
> db.mycollection.find({ '$xor': [ { 'a': 1 }, { 'b': 1 } ] })
(doesn't work - fictional syntax)
Does MongoDB support XOR logical operator? If not, how can it best be simulated?
MongoDB uses multi-granularity locking [1] that allows operations to lock at the global, database or collection level, and allows for individual storage engines to implement their own concurrency control below the collection level (e.g., at the document-level in WiredTiger).
MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array.
In MongoDB we recommend using the findAndModify command for this scenario. This command is atomic and thus lock the document for a status change. Each service instance should do: db.
MongoDB uses reader-writer locks that allow concurrent readers shared access to a resource, such as a database or collection, but in MMAPv1, give exclusive access to a single write operation.
Does this satisfy your expectation?
db.mycollection.find({ '$or': [ { 'a': 1 , 'b' : {$ne : 1} }, { 'b': 1, 'a' : {$ne : 1} } ] })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With