簡體   English   中英

使用NodeJS進行復雜的MongoDB集合查詢

[英]Complex MongoDB collection query with NodeJS

我在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次傳遞數據,但我想看看是否可以僅用一次完成。

尚未完全格式化:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM