【问题标题】:mongodb aggregate always return null in array of the collection objectmongodb 聚合总是在集合对象的数组中返回 null
【发布时间】:2020-06-21 11:12:31
【问题描述】:

我有这样的人, 这个人有很多公司,[ ONE TO MANY ]

{
        "_id" : ObjectId("5eef12533167638883fba5ad"),
        "companies" : [  
                         ObjectId("00000000000000000011111") , 
                         ObjectId("0000000000000000022222") 
                      ],
        "email" : "test@mailinator.com",
        "phoneNumber" : "+1689999999999",
        "createdAt" : ISODate("2020-06-21T07:54:56.529Z"),
        "updatedAt" : ISODate("2020-06-21T07:54:56.529Z")
}

我想将公司汇总到公司数据中 我正在尝试这样

db.people.aggregate(
  { "$lookup": {
    "from": "companies",
    "localField": "companies",
    "foreignField": "_id",
    "as": "companies"
  }},
)

但结果与查询 db.people.find() 相同 如何更正查询她在该数组中显示公司数据的方式,

我的预期是:

{
        "_id" : ObjectId("5eef12533167638883fba5ad"),
        "companies" : [  
                         {
                           "_id": ObjectId("00000000000000000011111"),
                            "name": "Company one"
                          },
                           ..... so on
                      ],
        "email" : "test@mailinator.com",
        "phoneNumber" : "+1689999999999",
        "createdAt" : ISODate("2020-06-21T07:54:56.529Z"),
        "updatedAt" : ISODate("2020-06-21T07:54:56.529Z")
}

【问题讨论】:

    标签: mongodb mongodb-query aggregate


    【解决方案1】:

    重要提示:从 MongoDB 3.4 开始,如果 localField 是一个数组,您可以将数组元素与标量 foreignField 进行匹配,而无需 $unwind 阶段。

    我认为您的汇总调用不正确。 .aggregate() 接收一个数组。

    db.people.aggregate([
      { 
       $lookup: {
        from: "companies",
        localField: "companies",
        foreignField: "_id",
        as: "companies"
       }
      }
    ])
    

    确保fromlocalFieldforeignField 正确。

    【讨论】:

    • 你是对的,我想知道为什么我的查询总是对公司为空,因为公司不在数据库中或已删除 LOL,哦,再一次,人公司的条件是什么,比如假设我想在该公司上个月创建的人中汇总公司??
    • 请参阅此文档。它描述了如何处理条件和多个连接。 docs.mongodb.com/manual/reference/operator/aggregation/lookup/…
    猜你喜欢
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2015-06-16
    • 2021-11-18
    • 1970-01-01
    相关资源
    最近更新 更多