Search code examples
node.jsmongodbmongojs

How to filter out the same keys that you $slice in mongodb


I have a collection as this:

[
{_id: "1234", myId: 1, a: [1,2,3], b: [23,3,2], c: [3,234,4], ...},
{_id: "5678", myId: 2, a: [21,32,3], b: [32,123,4], c: [32,32,12], ...},
{_id: "3242", myId: 3, a: [21,23,2], b: [12,2,32], c: [12,213,1], ...}
]

There are many more arrays in each of the document and also the size of each of these arrays is much larger. I want to be able to apply the $slice projection on two of my desired keys (to retrieve 50 latest values) and have only those two keys returned back, using mongo js.

I know how to do the tasks separately, but I'm unable to figure out an intersection of the two .

So using {a: {$slice: -50}, b: {$slice: -50}} as projection in the find() function will return me the last 50 entries, and {a: 1, b: 1} will return me only these two keys from the find() result.

How can I do both simultaneously?


Solution

  • You could try adding a dummy field in your projection:

    db.test.find({}, {a: {$slice: -2}, b: {$slice: -2}, dummy: 1, _id: 0})
    

    Returns

    /* 0 */
    {
        "a" : [ 2, 3 ],
        "b" : [ 3, 2 ]
    }
    
    /* 1 */
    {
        "a" : [ 32, 3 ],
        "b" : [ 123, 4 ]
    }
    
    /* 2 */
    {
        "a" : [ 23, 2 ],
        "b" : [ 2, 32 ]
    }