MongoDB filter by array property only if it exists

2019-09-02 20:49发布

问题:

My database object has an optional property named tags which is a string array. I want to write a query that returns objects if they match one of these conditions:

  1. They don't have a tags property.
  2. They have a tags property that has at least one item included in another array called queryTags

From reading the documentation I came up with the following but it doesn't work:

let query = {
    tags: { '$or': [{'$exists': false}, {'$in': queryTags}]}
}

回答1:

$or is a top-level operator, so your query needs to be:

let query = {
    '$or': [{tags: {'$exists': false}}, {tags: {'$in': queryTags}}]
}