簡體   English   中英

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

[英]How can I build a mongoDB query to find any of myArray ids inside a document field?

我在mongoDB上有一個具有以下架構的集合:

const ReceiptSchema = new Schema(
  {
    status: String,
    active: Boolean,
    name: String,
    companies: [Schema.Types.ObjectId],
    total: Number
  },
  { toJSON: { virtuals: true }, toObject: { virtuals: true } }
)

我在腳本中有以下id數組:

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] }}}
    ]
)

在mongo 3.4上

db.recip.aggregate(
    [
        {$addFields : {isMatches : {$gt : [{$size : {$setIntersection : ["$companies", ['abc']]}}, 0] }}},
        {$match : {isMatches : true}}
    ]
)

在低於3.4的版本$addFields更改$addFields $project

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM