【问题标题】:$concat on aggregate mongodb$concat 在聚合 mongodb 上
【发布时间】:2017-06-11 21:52:17
【问题描述】:

这有点令人困惑。 我正在尝试 $group aggregatation 的结果,而 grouping 他们创建新字段,其中包含两个不同字段的连接。唔。其实我不愿意分享数据库的结构并让你感到困惑。但描述不是解释性的。

所以我们开始吧。

学生收藏

{id: "1", school: "georgia tech"}

大学收藏

{name: "georgia tech" , state: "Georgia" , city: "Atlanta"}

我想得到什么?我想得到

{id: 1, name: "georgia tech" , place: "Georgia_Atlanta"}

我做了什么来实现这个目标?

db.student.aggregate([
    {$match: {"id": "1"}},
    {$lookup: {from: "university" , localField: "school" , foreignField: "name", as: "document"}},
    {$group: {_id: "$id", name: {$push: "$school"}, place: {$push: {$concat: ["$document.state" , "_" , "$document.city"]}}}}   
])

但这会引发错误;

assert: command failed: {
    "ok" : 0,
    "errmsg" : "$concat only supports strings, not Array",
    "code" : 16702
}

同时;

db.student.aggregate([
    {$match: {"id": "1"}},
    {$lookup: {from: "university" , localField: "school" , foreignField: "name", as: "document"}},
    {$group: {_id: "$id", name: {$push: "$school"}, place: {$push: "$document.state" }}}    
])

返回为;

{ "_id" : "1", "name" : [ "georgia tech" ], "place" : [ [ "Georgia" ] ] }

问题在于连接statecity 字段。 所以这里再次提出问题。如何连接 document.state_document.city

【问题讨论】:

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


    【解决方案1】:

    我不知道确切的用例,但如果您需要使用 GroupBy,这是工作版本。否则,chridam 正在使用更简单的方法:

    db.student.aggregate([
        {$match: {"id": "1"}},
        {$lookup: {from: "university" , localField: "school" , foreignField: "name", as: "document"}},
        {$group: {_id: "$id", name: {$first: "$school"}, tempplace: {$first: "$document" }}},
        {$unwind: "$tempplace"},
        {$project: {id: 1, name: 1, place: {$concat: ["$tempplace.state", "_", "$tempplace.city"]}}}
    ])
    

    【讨论】:

      【解决方案2】:

      $lookup 返回一个数组,因此您需要使用 $arrayElemAt 运算符将其展平(如果它有单个元素)或 $unwind(如果它有多个元素)。所以最后,您应该能够运行以下管道以获得所需的结果:

      db.student.aggregate([
          { "$match": { "id": "1" } },
          {
              "$lookup": {
                  "from": "university", 
                  "localField": "school", 
                  "foreignField": "name", 
                  "as": "document"
              }
          },
          {
              "$project": {
                  "id": 1,
                  "university": { "$arrayElemAt": [ "$document", 0 ] }
              }
          },
          {
              "$project": {
                  "id": 1,
                  "name": "$university.name",
                  "place": { "$concat": ["$university.state", "_", "$university.city"] }
              }
          }    
      ])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        • 2018-06-16
        • 2018-05-31
        • 2017-08-18
        • 1970-01-01
        • 2021-04-28
        • 2016-04-29
        相关资源
        最近更新 更多