这是我第一次使用mongo进行流星项目,这是为了帮助一群用户合作阅读圣经。该集合的数据结构如下所示:
//collection is named as 'logs'
[
{
_id: someObjectId,
startPage: 1,
finishPage: 4,
status: 'in progress',
userId: someUserId1
},
{
_id: someObjectId,
startPage: 5,
finishPage: 10,
status: 'done',
userId: someUserId2
}
//.... and so on and normally two users wont read the same page.
]
我想弄清楚以下内容:
由于我对mongo的了解有限,我现在陷入了困境。我一直在寻找各种解决方案,但不确定哪种解决方案合适:
e.g。
[
{
page: 1,
inProgress: 0, //users would normally not read the same page twice but they may
done: 1
},
{
page: 2,
inProgress: 1, //users would normally not read the same page twice but they may
done: 0
}
]
如果有人能够提供一些有关这种和首选方法的见解,我将非常感激。这可能是显而易见的,但我发现它有点困难。感谢。
答案 0 :(得分:2)
我尝试根据您尝试实现的用途对文档进行建模。如果您将日志拆分为仅读取的页面,那么您可以执行一个简单的分组。
所以说我们将你的模型更改为以下内容:
[{
_id: new ObjectId(),
pageNumber: 1,
status: 'in progress',
userId: 1
},
{
_id: new ObjectId(),
pageNumber: 2,
status: 'in progress',
userId: 1
},
{
_id: new ObjectId(),
pageNumber: 3,
status: 'in progress',
userId: 1
},
{
_id: new ObjectId(),
pageNumber: 4,
status: 'in progress',
userId: 1
},
{
_id: new ObjectId(),
pageNumber: 5,
status: 'in progress',
userId: 1
},
{
_id: new ObjectId(),
pageNumber: 6,
status: 'done',
userId: 2
},
{
_id: new ObjectId(),
pageNumber: 7,
status: 'done',
userId: 2
},
{
_id: new ObjectId(),
pageNumber: 8,
status: 'done',
userId: 2
},
{
_id: new ObjectId(),
pageNumber: 9,
status: 'done',
userId: 2
},
{
_id: new ObjectId(),
pageNumber: 10,
status: 'done',
userId: 2
},
{
_id: new ObjectId(),
pageNumber: 9,
status: 'done',
userId: 1
},
{
_id: new ObjectId(),
pageNumber: 10,
status: 'done',
userId: 1
}]
然后我们可以运行以下聚合查询:
> db.logs.aggregate([ {$group: { _id: { "pageNumber" : "$pageNumber", "status" : "$status"}, count : {$sum : 1}}} ]).pretty()
{ "_id" : { "pageNumber" : 8, "status" : "done" }, "count" : 1 }
{ "_id" : { "pageNumber" : 7, "status" : "done" }, "count" : 1 }
{ "_id" : { "pageNumber" : 6, "status" : "done" }, "count" : 1 }
{ "_id" : { "pageNumber" : 4, "status" : "in progress" }, "count" : 1 }
{ "_id" : { "pageNumber" : 9, "status" : "done" }, "count" : 2 }
{ "_id" : { "pageNumber" : 3, "status" : "in progress" }, "count" : 1 }
{ "_id" : { "pageNumber" : 10, "status" : "done" }, "count" : 2 }
{ "_id" : { "pageNumber" : 2, "status" : "in progress" }, "count" : 1 }
{ "_id" : { "pageNumber" : 5, "status" : "in progress" }, "count" : 1 }
{ "_id" : { "pageNumber" : 1, "status" : "in progress" }, "count" : 1 }