mongodb limit in the embedded document

后端 未结 2 692
庸人自扰
庸人自扰 2021-02-09 07:44

I need to create a message system, where a person can have a conversation with many users. For example I start to speak with user2, user3 and user4, so anyone of them can see th

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-09 07:55

    The MongoDB docs explain how to select a subrange of an array element.

    db.dialogs.find({"_id": [dialogId]}, {msgs:{$slice: 5}}) // first 5 comments
    db.dialogs.find({"_id": [dialogId]}, {msgs:{$slice: -5}}) // last 5 comments
    db.dialogs.find({"_id": [dialogId]}, {msgs:{$slice: [20, 10]}}) // skip 20, limit 10
    db.dialogs.find({"_id": [dialogId]}, {msgs:{$slice: [-20, 10]}}) // 20 from end, limit 10
    

    You can use this technique to only select the messages that are relevant to your UI. However, I'm not sure that this is a good schema design. You may want to consider separating out "visible" messages from "archived" messages. It might make the querying a bit easier/faster.

提交回复
热议问题