如何在函数更新中结合 $slice 和 select 返回键操作? [英] How to combine both $slice and select returned keys operation in function update?
问题描述
给定集合如下:
> 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 }
我需要在 find 函数中结合 {fruit : {$slice : 2}} 和 {fruit : 1} .这是我尝试过的,没有一个像我预期的那样工作.
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" ] }
推荐答案
很遗憾,您正在寻找的功能无法使用.
Unfortunately, the feature you're looking for will not work.
您是说您想要果园和一片果园.{fruit: 1,fruit: {$slice : 2}
但这会创建无效的 JSON,因为您两次使用相同的密钥.
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:
排除所有其他字段:
> db.food.find({}, {fruit : {$slice : 2}, _id : 0, size : 0, ...})
进行权衡并在返回中包含 _id
字段:
Make a trade-off and also include the _id
field in the return:
> db.food.find({}, {fruit : {$slice : 2}, _id : 1})
我在此处发现了 JIRA 问题.看起来 10gen 的员工想要这种行为.
I found the JIRA issue for this here. It looks like the 10gen staff want this behavior.
这篇关于如何在函数更新中结合 $slice 和 select 返回键操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!