获取数组中的第一个元素并使用Aggregate返回? [英] Get first element in array and return using Aggregate?
问题描述
如何使用Mongo聚合获取并返回数组中的第一个元素?
我尝试使用此代码:
db.my_collection.aggregate([
{ $project: {
resp : { my_field: { $slice: 1 } }
}}
])
但出现以下错误:
uncaught exception: aggregate failed: {
"errmsg" : "exception: invalid operator '$slice'",
"code" : 15999,
"ok" : 0
}
请注意,'my_field'
是一个由4个元素组成的数组,我只需要返回第一个元素.
Note that 'my_field'
is an array of 4 elements, and I only need to return the first element.
推荐答案
当前,$slice
运算符在聚合管道的$project
操作中不可用.
因此,您可以做的是
Currently, the $slice
operator is unavailable in the the $project
operation, of the aggregation pipeline.
So what you could do is,
首先是$unwind
,是my_field
数组,然后将它们分组在一起,并采用该组的$first
元素.
First $unwind
, the my_field
array, and then group them together and take the $first
element of the group.
db.my_collection.aggregate([
{$unwind:"$my_field"},
{$group:{"_id":"$_id","resp":{$first:"$my_field"}}},
{$project:{"_id":0,"resp":1}}
])
或使用find()
命令,您可以在projection
部分中使用$ slice运算符.
Or using the find()
command, where you could make use of the $slice operator in the projection
part.
db.my_collection.find({},{"my_field":{$slice:1}})
更新:根据您的评论,假设您只希望数组中的second
项用于ID为id
的记录.
Update: based on your comments, Say you want only the second
item in an array, for the record with an id, id
.
var field = 2;
var id = ObjectId("...");
然后,下面的聚合命令为您提供带有_id
,id
的记录的my_field
数组中的第二项.
Then, the below aggregation command gives you the 2nd item in the my_field
array of the record with the _id
, id
.
db.my_collection.aggregate([
{$match:{"_id":id}},
{$unwind:"$my_field"},
{$skip:field-1},
{$limit:1}
])
以上逻辑不能用于更多记录,因为它会在$unwind
之后包含一个$group
运算符. $group
运算符为该特定组中的所有记录生成单个记录,从而使得在以后阶段应用的$limit
或$skip
运算符无效.
The above logic cannot be applied for more a record, since it would involve a $group
, operator after $unwind
. The $group
operator produces a single record for all the records in that particular group making the $limit
or $skip
operators applied in the later stages to be ineffective.
在上面的find()
查询中进行小的改动也会产生预期的结果.
A small variation on the find()
query above would yield you the expected result as well.
db.my_collection.find({},{"my_field":{$slice:[field-1,1]}})
除了这些之外,总有一种方法可以在客户端进行,尽管如果记录数量很大,则可能会花费很多:
Apart from these, there is always a way to do it in the client side, though a bit costly if the number of records is very large:
var field = 2;
db.my_collection.find().map(function(doc){
return doc.my_field[field-1];
})
从以上选项中进行选择取决于您的数据大小和应用程序设计.
Choosing from the above options depends upon your data size and app design.
这篇关于获取数组中的第一个元素并使用Aggregate返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!