gpt4 book ai didi

MongoDB 分组依据

转载 作者:可可西里 更新时间:2023-11-01 09:28:08 25 4
gpt4 key购买 nike

我如何在 Mongodb 中进行查询以查找某个位置的用户进入和退出组的计数。上述集合有许多用户可以进入或退出的位置。

{ "ActivityList" : [ 
{ "type" : "entry",
"timestamp" : Date( 1344473257320 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "exit",
"timestamp" : Date( 1348792321111 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "entry",
"timestamp" : Date( 1348881701129 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "exit",
"timestamp" : Date( 1348942808700 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "entry",
"timestamp" : Date( 1348957400052 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } },
{ "type" : "exit",
"timestamp" : Date( 1349024290729 ),
"user" : { "$ref" : "userProfile",
"$id" : ObjectId( "4fdeaf6fde26fd298262bb81" ) } } ],
"Loc" : { "$ref" : "location",
"$id" : ObjectId( "501cb6d4e7e9a8f958f903c5" ) },
"_id" : ObjectId( "502308a9e7e91ab176f6708e" ) }

我正在尝试类似的方法但没有成功,see here

select a,b,sum(c) csum from coll where active=1 group by a,b



db.coll.group(
{key: { a:true, b:true },
cond: { active:1 },
reduce: function(obj,prev) { prev.csum += obj.c; },
initial: { csum: 0 }
});

最佳答案

您正在使用的文档结构(项目数组)将需要在 $group() 函数中进行一些操作,使用 MapReduce 或新的 Aggregation Framework 可以更轻松地完成这些操作在 MongoDB 2.2 中。

这是一个使用聚合框架的示例:

db.activity.aggregate(

// Find matching documents first (can take advantage of index)
{ $match : {
Loc: DBRef("location", ObjectId("501cb6d4e7e9a8f958f903c5"))
}},

// Unwind the ActivityList array as a document stream
{ $unwind : "$ActivityList" },

// Group the stream by activity types for a user
{ $group : {
_id : "$ActivityList.user",
activity: { $push: "$ActivityList.type" }
}},

// Unwind the activity types so they can be counted
{ $unwind : "$activity" },

// Final grouping: count of action (entry or exit) for each user
{ $group : {
_id : { user: "$_id", action: "$activity" },
count: { $sum: 1 }
}}
)

产生的结果类似于:

{
"result" : [
{
"_id" : {
"user" : DBRef("userProfile", ObjectId("4fdeaf6fde26fd298262bb81")),
"action" : "exit"
},
"count" : 6
},
{
"_id" : {
"user" : DBRef("userProfile", ObjectId("4fdeaf6fde26fd298262bb81")),
"action" : "entry"
},
"count" : 3
},
{
"_id" : {
"user" : DBRef("userProfile", ObjectId("4fdeaf6fde26fd298262bb82")),
"action" : "entry"
},
"count" : 2
},
{
"_id" : {
"user" : DBRef("userProfile", ObjectId("4fdeaf6fde26fd298262bb85")),
"action" : "entry"
},
"count" : 1
}
],
"ok" : 1
}

关于MongoDB 分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12721787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com