【问题标题】:How to match 2 fields in Mongo collection with one of the field being inside an array如何将 Mongo 集合中的 2 个字段与数组中的一个字段匹配
【发布时间】:2020-06-16 15:40:28
【问题描述】:

我有一个集合 Items 的对象说:

[{"Item" : "Apple",
  "Company" : "American Foods",
  "Items" : [{"name" : "Banana", "name" : "Orange", "name" : "Apple", "name" : "Avocado"}]},
 {"Item" : "Mango",
  "Company" : "American Foods",
  "Items" : [{"name" : "Banana", "name" : "Orange", "name" : "Apple", "name" : "Avocado"}]},
 {"Item" : "Banana",
  "Company" : "Indian Foods",
  "Items" : [{"name" : "Banana", "name" : "Orange", "name" : "Apple", "name" : "Avocado"}]}
]

我想编写一个 mongo 聚合查询,它接受一个输入来返回与任何 Item = Items[i].nameCompany = input 匹配的所有文档。

假设如果我使用input = American Foods 搜索,那么查询将返回集合中的 1 个文档(因为芒果不存在于 Items 中,而 Banana 的公司是 Indian Foods):

{"Item" : "Apple",
  "Company" : "American Foods",
  "Items" : [{"name" : "Banana", "name" : "Orange", "name" : "Apple", "name" : "Avocado"}]}

【问题讨论】:

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您需要使用$expr 运算符:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          {
            $eq: [ "$Company", "American Foods"]
          },
          {
            $in: [ "$Item", "$Items.name" ]
          }
        ]
      }
    }
  }
])

MongoPlayground

注意:你的Items数组有错误的JSON语法,它应该有单独的项目

【讨论】:

  • 是的,对不起。我才发现。谢谢
【解决方案2】:

Nodejs + Mongoose

你可以试试这个方法吗?

var input = "American Foods";
Items.find({},function(err, list_items){
    if(err){
        console.log("err: " + err);
    }else{
        if(list_items.length > 0){
            list_items.forEach(item_tmp => {
                Items.find( { Company : input,"Items": { name:  item_tmp.Item} }, function(err, data){
                    // doing something
                } )
            })
        }
    }
})

【讨论】:

    猜你喜欢
    • 2020-10-01
    • 1970-01-01
    • 2015-07-28
    • 2021-08-19
    • 1970-01-01
    • 2016-07-20
    • 2020-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多