使用NodeJS进行复杂的MongoDB集合查询

时间:2017-04-18 13:24:24

标签: javascript node.js mongodb mongoose

我在MongoDB中有大量文档集合,以下结构为例:

{ "key" : "a" ,"data" : "value1" , "lastname" : "Doe" }<br>
{ "key" : "ab" , "data" : "value1" , "lastname" : "Doe" }<br>
{ "key" : "abc" ,   "data" : "value1" , "lastname" : "Doe" } <<< <br>
{ "key" : "d" ,     "data" : "value2" , "lastname" : "Doe" }<br>
{ "key" : "df" ,    "data" : "value2" , "lastname" : "Doe" }<br>
{ "key" : "dfg" ,   "data" : "value2" , "lastname" : "Doe" } <<< <br>

我需要根据这些行<<<的条款从key标记的这两行中获取数据 已包含来自同一lastname的其他文档的键值,即“abc”具有“ab”而“ab”具有“a”,我需要的结果应如下所示:

{ "lastname" : "Doe" , "value1" : "abc" , "value2" : "dfg" }

我可以通过创建2个单独的查询来提取2个数据中的数据,但我想看看是否可以只在一个中完成。

1 个答案:

答案 0 :(得分:0)

尚未完全格式化:

db.coll.aggregate([
 {$project: {key:1, root: '$$ROOT', lastname: 1, data: 1, keyLength: {$strLenBytes: '$key'}, keyIndexes: {$range:[0,  {$strLenBytes: '$key'}]}}}, 
 {$unwind: '$keyIndexes'}, 
 {$group: {items: {$push: '$root'}, count: {$sum: 1}, _id: {$substrBytes: ['$key', '$keyIndexes', 1]}}}, 
 {$match: {count: 1}}, 
 {$group: {_id: '$items.lastname', items: {$push: {$arrayElemAt: ['$items', 0]}}}}
]).pretty()
{
    "_id" : [
        "Doe"
    ],
    "items" : [
        {
            "_id" : ObjectId("58f62e5433530ab32f554fd6"),
            "key" : "abc",
            "data" : "value1",
            "lastname" : "Doe"
        },
        {
            "_id" : ObjectId("58f62e5433530ab32f554fd9"),
            "key" : "dfg",
            "data" : "value2",
            "lastname" : "Doe"
        }
    ]
}