开发者

How to combine both $slice and select returned keys operation in function update?

Given the collection as follows:

> db.food.find()
{ "_id" : 1, "fruit" : [ "apple", "banana", "peach", "strawberry", "grape" ], "size" : 2 }
{ "_id" : 2, "fruit" : [ "apple", "kumquat", "orange", "strawberry", "grape" ], "size" : 2 }
{ "_id" : 3, "fruit" : [ "cherry", "banana", "apple", "strawberry", "grape" ], "size" : 2 }

I need to combine {fruit : {$slice : 2}} and {fruit : 1} in the find function. Here is what I have tried, none of them works the way I expected.

> db.food.find({}, {fruit : {$slice : 2}, fruit : 1, _id : 0})
{ "fruit" : [ "apple", "banana", "peach", "strawberry", "grape" ] }
{ "fruit" : [ "apple", "kumquat", "orange", "strawberry", "grape" ] }
{ "fruit" : [ "cherry", "banana", "apple", "strawberry", "grape" ] }
This method ONLY works for {fruit : 1, _id : 0}

> db.food.find({}, {fruit : 1, fruit : {$slice : 2}, _id : 0})
{ "fruit" : [ "apple", "banana" ], "size" : 2 }
{ "fruit" : [ "apple", "kumquat" ], "size" : 2 }
{ "fruit" : [ "cherry", "banana" ], "size" : 2 }
This method ONLY works for {fruit : {$slice : 2}}

> db.food.find({}, {$and : [{fruit : 1}, {fruit : {$slice : 1}}]})
{ "_id" : 1 }
{ "_id" : 2 }
{ "_id" : 3 }

I even don't know why the return results look like this

To make it clear, here is what I want to get:

{ "fruit" : [ "apple", "banana" ]  }
{ "fruit" : [ "apple", "kumquat" ] }
{ "fruit" : [ "cherry", "banana" ] }
开发者_StackOverflow社区


Unfortunately, the feature you're looking for will not work.

You're saying that you want both the fruit field and a slice of the fruit field. { fruit: 1, fruit: {$slice : 2} But that creates invalid JSON as you have the same key twice.

From your examples, it looks like the intent is to have the fruit and only the fruit. Unfortunately, there are only two options for this:

Exclude all other fields:

> db.food.find({}, {fruit : {$slice : 2}, _id : 0, size : 0, ...})

Make a trade-off and also include the _id field in the return:

> db.food.find({}, {fruit : {$slice : 2}, _id : 1})

I found the JIRA issue for this here. It looks like the 10gen staff want this behavior.


I think there's no such a way to do this without explicitly including _id:0, _size:0 in the 2nd argument for find().

from MongoDB Definitive Guide :

Unless otherwise specified, all keys in a document are returned when "$slice" is used. This is unlike the other key specifiers(for ex: fruit:1), which suppress unmentioned keys from being returned.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜