mongodb:匹配字符串或数组

时间:2018-11-12 01:06:30

标签: 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')" })

0 个答案:

没有答案