[英]How can I build a mongoDB query to find any of myArray ids inside a document field?
I have on a mongoDB, a collection with the following schema: 我在mongoDB上有一个具有以下架构的集合:
const ReceiptSchema = new Schema(
{
status: String,
active: Boolean,
name: String,
companies: [Schema.Types.ObjectId],
total: Number
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
)
And I have on my script the following ids Array: 我在脚本中有以下id数组:
myArray = ['abc', 'def', 'ghi']
How can I build a query to get all the documents fro Receipt schema that contains some of the ids on my array, inside the field companies ? 我该如何建立查询以从收据架构中获取所有文档,这些收据架构包含我在现场公司内部的数组中的某些ID?
Any idea? 任何想法? Thanks
谢谢
You can use $setIntersection
to find any matching array element in companies array 您可以使用
$setIntersection
在公司数组中查找任何匹配的数组元素
on mongo 3.6+ 在mongo 3.6+
find 找
db.recip.find({$expr : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }})
aggregate 骨料
db.recip.aggregate(
[
{$match : {$expr : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }}}
]
)
on mongo 3.4 在mongo 3.4上
db.recip.aggregate(
[
{$addFields : {isMatches : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }}},
{$match : {isMatches : true}}
]
)
change $addFields
to $project
in mongo version less than 3.4 在低于3.4的版本
$addFields
更改$addFields
$project
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.