我需要将结果中的“browser”键的值作为字典数组。我当前的查询返回一个字典数组的数组,这不是我想要的。
以下是我的数据,查询和我当前的结果:
{
"_id" : ObjectId("52f11293ed50ed92d0324755"),
"major" : "26",
"site_domain" : "www.google.com",
"user_id" : "34850348039485093455445434",
"timestamp" : "1390953411",
"browser_name" : "Firefox",
}
db.collection.aggregate({$group:{_id: {user_id:"$user_id", site_domain:"$site_domain"}, browser: {$addToSet:{name:"$browser_name", type:"$major"}}, browsing_history: {$addToSet:"$timestamp"}}},
{$group:{_id: {user_id:"$_id.user_id"}, browser:{$addToSet:"$browser"}, sites_visited:{$addToSet:{ site:"$_id.site_domain", times:"$browsing_history"}}}});
{
"_id" : {
"user_id" : "ab93680ffb1b9c2"
},
"browser" : [
[
{
"name" : "Firefox",
"type" : "20"
}
]
],
"sites_visited" : [
{
"site" : "google.com",
"times" : [
[
"20140201105126",
"1167637060"
]
]
}
]
}
“浏览器”键的理想结果是:
"browser" : [
{
"name" : "Firefox",
"type" : "20"
}
]
答案 0 :(得分:1)
你大部分都是这样。只需在其间添加$unwind即可。请记住,否则您将数组推送到另一个数组。
db.collection.aggregate([
{$group:{
_id: {user_id:"$user_id", site_domain:"$site_domain"},
browser: {$addToSet:{name:"$browser_name", type:"$major"}},
browsing_history: {$addToSet:"$timestamp"}
}},
{$unwind: "$browser"}, // de-normalize before next group
{$group:{
_id: {user_id:"$_id.user_id"},
browser:{$addToSet:"$browser"},
sites_visited:
{$addToSet:{ site:"$_id.site_domain", times:"$browsing_history"}}
}}
]);