首页 > 解决方案 > mongodb:匹配字符串或数组

问题描述

mongodb 提供了这种语法来匹配一个字符串:

db.inventory.find( { tags: "red" } )

所以它会匹配:

{ "_id" : ObjectId("xxx"), "tags" : "red" }

但它也会匹配数组中的一个元素:

{ "_id" : ObjectId("xxx"), "tags" : [ "blank", "red" ] }

那么我如何匹配数组中的字符串或元素但不能同时匹配两者?

我知道我可以使用$where,但出于显而易见的原因,我更喜欢更简单的方法(如果有的话):

db.inventory.find({ "$where": "this.tags == 'red'" })
db.inventory.find({ "$where": "Array.isArray(this.tags) && this.tags.includes('red')" })

标签: mongodb

解决方案


推荐阅读