简体   繁体   English

如何建立mongoDB查询以在文档字段中找到任何myArray id?

[英]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.

相关问题 我如何按MongoDB文档中的字段对数组排序 - How can I sort array by a field inside a MongoDB document 如何在MongoDB的集合中找到两个时间字段之间的差异并将结果添加到同一文档中? - How can I find the difference between two time fields and add the result in the same document, inside a collection at MongoDB? 如何查询mongodb以获取包含$ in存储在我的`var ids`数组中的ID的文档? - How can I query mongodb for documents that ids are stored in my `var ids` array with $in? MongoDB 查找匹配文档并更新对象数组中的匹配字段 - MongoDB find matching document and update matching field inside array of objects MongoDB-如何使用[Object]作为字段构建查询字符串 - MongoDB - How to build query string with [Object] as a field 我如何通过节点js在mongodb中找到不同的字段 - how can i find distinct field in mongodb through node js 如何使用MongoDB查找与自定义字段匹配的文档? - How can I use MongoDB to find documents that match with custom field? 我如何找到 mongodb 数组中是否存在字符串 - How I can find if string exists inside mongodb Array 我正在尝试遍历一组ID,如果不存在ID则插入一个mongodb文档。 我如何让他们坚持下去? - I am trying to iterate through an array of ids and insert a mongodb document if an id is not present. How can i get them to persist? 我有一个 id 数组,需要更新对象文档 mongodb 内数组中的匹配对象,如果没有,则插入 - I have an array of ids and need to update matching object in array inside the object document mongodb if not then insert
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM