简体   繁体   English

如何在 MongoDB 中使用聚合查找数组中的 object?

[英]How to lookup object in array with aggregation in MongoDB?

I'm using aggregate([...]) method to select documents from MongoDB, but I have a problem with $lookup , I can't get the results of the reference field info after query, it not works because it always return empty array.我正在对来自 MongoDB 的 select 文档使用aggregate([...])方法,但是我对$lookup有问题,查询后我无法获得参考字段info的结果,它不起作用,因为它总是返回空数组。 How can i solve this problem?我怎么解决这个问题?

My MongoSchema config:我的 MongoSchema 配置:

const PostModel = new Schema({
  ...,
  info: [
    {
      label: {
        type: ObjectId,
        ref: 'catalogs',
        required: true           
      },
      value: {
        type: ObjectId,
        ref: 'attributes', 
        required: true           
      }
    }
  ],
  ...
})

My code for execute aggregate to query collection:我执行聚合查询集合的代码:

  const doc = await PostModel.aggregate([    
    {
      "$lookup": {
        "from": "catalogs",  
        "localField": "info.label",  
        "foreignField": "_id",
        "as": "infoLabel"
      }
    },           
    {
      "$lookup": {
        "from": "attributes",  
        "localField": "info.value",  
        "foreignField": "_id",
        "as": "infoValue"
      }
    },                  
    {
      "$project": {
        info: {
          label: '$infoLabel',
          value: '$infoValue'
        }
      }
    }  
  ])

  console.log(doc) // it always return empty array :(

You need to first unwind the info then use lookup query that will work您需要先展开信息,然后使用可行的查找查询

{ $unwind:"$info" },
{ $lookup:{ ... } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM