我在mongoDB上有一个具有以下模式的集合:
const ReceiptSchema = new Schema(
{
status: String,
active: Boolean,
name: String,
companies: [Schema.Types.ObjectId],
total: Number
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
)
我的脚本上有以下 ids 数组:
myArray = ['abc', 'def', 'ghi']
如何构建查询以从包含我的数组上的一些 ID 的收据架构获取所有文档,在现场公司内部?
知道吗?谢谢
您可以使用 $setIntersection
在公司数组中查找任何匹配的数组元素
在 MONGO 3.6+ 上
找到
db.recip.find({$expr : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }})
骨料
db.recip.aggregate(
[
{$match : {$expr : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }}}
]
)
在蒙戈 3.4 上
db.recip.aggregate(
[
{$addFields : {isMatches : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }}},
{$match : {isMatches : true}}
]
)
在低于 3.4 的 MONGO 版本中将$addFields
更改为 $project