![](/img/trans.png)
[英]Complex query using 2 separate collections in Mongodb / Nodejs
[英]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.