Mongo aggregate()无限滚动,剩余项目

时间:2018-02-23 20:20:42

标签: mongodb-query

我对mongo聚合管道并不熟悉,但这就是我想要做的和我尝试过的,

我有userparticipantconversation个收藏。

  • 用户拥有externalUserId
  • 对话有_id
  • 参与者有conversationIdexternalUserId

我正在尝试获取用户的对话,并想要无限滚动分页。

给定externalUserIdbefore时间,我正在做,

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*/
  ]
}

0 个答案:

没有答案