MongoDB子文档查询限制元素

时间:2013-04-13 22:28:18

标签: mongodb mongoose aggregation-framework

这是我的文档的样子。

{
    ID: "XYZ",
    messages: [
        {
            ID: "AAA",
            text: "this is a message"
        },
        {
            ID: "BBB",
            text: "this is a message"
        },
        {
            ID: "CCC",
            text: "this is a message"
        },
        {
            ID: "DDD",
            text: "this is a message"
        },
        {
            ID: "EEE",
            text: "this is a message"
        },
        {
            ID: "FFF",
            text: "this is a message"
        },
        {
            ID: "GGG",
            text: "this is a message"
        }
    ]
}

我想汇总并获取消息,例如从CCCFFF

{
    ID: "XYZ",
    messages: [
        {
            ID: "CCC",
            text: "this is a message"
        },
        {
            ID: "DDD",
            text: "this is a message"
        },
        {
            ID: "EEE",
            text: "this is a message"
        },
        {
            ID: "FFF",
            text: "this is a message"
        }

    ]
}

那怎么可能呢?

1 个答案:

答案 0 :(得分:2)

这可以通过使用$ slice运算符来实现。 Check out the mongodb documentation on $slice。 运行查询以获取文档并使用带有查询的切片运算符:

query.slice('messages', [numOfElementsToSkip, numOfElementsToReturn]);

或者更具体地针对您的请求:

query.slice('messages', [2, 4]); // Return 4 elements after skipping 2