Javascript 带有NodeJS的复杂MongoDB集合查询
我在Javascript 带有NodeJS的复杂MongoDB集合查询,javascript,node.js,mongodb,mongoose,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> { "ke
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>
通过创建两个单独的查询,我可以在两个过程中提取数据,但我想看看这是否可以在一个过程中完成。尚未完全格式化:
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"
}
]
}
可能重复的
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"
}
]
}