MongoDB filter by array property only if it exists

时间秒杀一切 提交于 2019-12-11 18:15:12

问题


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}}]
}


来源:https://stackoverflow.com/questions/51403361/mongodb-filter-by-array-property-only-if-it-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!