当前位置:  开发笔记 > 编程语言 > 正文

聚合mongodb $ concat

如何解决《聚合mongodb$concat》经验,为你挑选了1个好方法。

这有点令人困惑.我正在尝试$group结果,aggregatationgrouping我们创造了新的领域,其中包括两个不同领域的结合.嗯.实际上我不愿意分享数据库的结构并让你感到困惑.但描述并不是解释性的.

所以我们走了.

学生集合

{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田地相结合.所以这里的问题又来了.我怎样才能Concat的document.state,_document.city



1> chridam..:

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

推荐阅读
oDavid_仔o_880
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有