Home > Enterprise >  (Boolean logic) What is a workaround for duplicate keys when working with boolean logic in MongoDB?
(Boolean logic) What is a workaround for duplicate keys when working with boolean logic in MongoDB?

Time:11-22

When I'm trying to query for several categories in a database, such as:

Example: {
  "AttributeA": type,
  "AttributeB": type,
  "AttributeC": type,
  "AttributeD": type
etc...
}

And say that I'm trying to query for samples that have (AttributeA matching criteria1 or AttributeB matching criteria2) and (AttributeC matching criteria3, 4, 5, or 6). How would we compose the .find() method in MongoDB to match without error or complicated boolean algebra (distributing out the "and")?

I've tried using notation such as:

db.Example.find({
  $or:[{"AttributeA" : criteria1, "AttributeB" : criteria2}],
  $or:[{"AttributeC" : criteria3, "AttributeC" : criteria4, ...}]
})

in an attempt for an easy query satisfying the conditions above, but in some cases this would result in only one condition of the query being satisfied (giving a "duplicate key '$or'" warning before compiling) and in other instances (different platforms) this straight up gives an error along the lines of the warning.

CodePudding user response:

If I understood the question correctly, I think you are looking for a query predicate such as:

{
  $or: [
    {
      AttributeA: "criteria1"
    },
    {
      AttributeB: "criteria2"
    }
  ],
  AttributeC: {
    $in: [
      "criteria3",
      "criteria4",
      "criteria5"
    ]
  }
}

See how it works on this playground example

How would we compose the .find() method in MongoDB to match without ... complicated boolean algebra (distributing out the "and")?

By default, MongoDB applies an implicit $and operator to query predicates at the same level. There is an explicit operator also available, but it is not needed in your situation. You can allow the database to distribute the condition(s) that is logically $anded for you.

AttributeC matching criteria3, 4, 5, or 6

This is a perfect use for the $in operator, which I've used in the query above as:

AttributeC: {
    $in: [ "criteria3", "criteria4", "criteria5" ]
  }
  • Related