1

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?

maazadeeb
  • 5,922
  • 2
  • 27
  • 40

1 Answers1

1

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 ]
}
chridam
  • 100,957
  • 23
  • 236
  • 235
  • can you explain more this `dummy: 1`? why you put in projection? any documentation link about `dummy` ? – Neo-coder Apr 30 '15 at 11:27
  • @yogesh It's a bit of a workaround where you project a non-existing field (it can be any name as long as it's not part of your document schema) alongside the [**`$slice`**](http://docs.mongodb.org/manual/reference/operator/projection/slice/#slice-projection) projected arrays. There is no documentation yet for this. – chridam Apr 30 '15 at 11:33
  • 1
    Thank you so much! Worked like a charm! – maazadeeb May 02 '15 at 16:33