我对mongo聚合管道并不熟悉,但这就是我想要做的和我尝试过的,
我有user
,participant
和conversation
个收藏。
externalUserId
。_id
。conversationId
和externalUserId
。我正在尝试获取用户的对话,并想要无限滚动分页。
给定externalUserId
和before
时间,我正在做,
db.participant.aggregate([
{
$match : {
externalUserId:'some-external-user-id',
/*Potentially other participant-related conditions*/
archived : false
}
},
{
$lookup : {
localField:"conversationId",
from:"conversation",
foreignField:"_id",
as:"conversation"
}
},
{
$match : {
"conversation.createdOrLastMessageAt" : {
$lt:ISODate("some-before-date")
},
/*Potentially other conversation-related conditions*/
"conversation.creationSuccessful":true,
}
},
{
$sort : {
"conversation.createdOrLastMessageAt" : -1
}
},
{ $limit:5 }, //The limit; arbitrary
{ $unwind : "$conversation" },
{
$project : {
_id:"$conversation._id",
createdOrLastMessageAt:"$conversation.createdOrLastMessageAt",
creationSuccessful:"$conversation.creationSuccessful",
/*Potentially other conversation-related data*/
data:"$conversation.data",
}
}
]).pretty()
这很好用,给我一些文件,
[
{
_id : ObjectId("some-id"),
createdOrLastMessageAt : ISODate("some-date"),
creationSuccessful : true,
data : {}
},
/*snip, other items*/
]
但是,我发现自己必须进行第二次查询以获取剩余项目的金额,
db.participant.aggregate([
{
$match : {
externalUserId:'some-external-user-id',
/*Potentially other participant-related conditions*/
archived : false
}
},
{
$lookup : {
localField:"conversationId",
from:"conversation",
foreignField:"_id",
as:"conversation"
}
},
{
$match : {
"conversation.createdOrLastMessageAt" : {
$lt:ISODate("some-before-date")
},
/*Potentially other conversation-related conditions*/
"conversation.creationSuccessful":true,
}
},
{ $count : "items-before-some-date" }
]).pretty()
哪个给了我,
{ "items-before-some-date" : 9001 }
然后我只需要items-before-some-date
- items-retrieved-in-step-1
来获取剩余的商品。
一切正常,但我只是想知道是否有办法构建我的聚合查询,以便在一个查询中得到
{
//items-before-some-date - items-retrieved-in-step-1, hopefully?
//I don't mind if I get just "items-before-some-date",
//I can do the subtraction on the server/client side
itemsLeft : 8996,
items : [
{
_id : ObjectId("some-id"),
createdOrLastMessageAt : ISODate("some-date"),
creationSuccessful : true,
data : {}
},
/*snip, other items*/
]
}