获取数组中的第一个元素并使用聚合返回? [英] 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("...");
然后,下面的聚合命令为您提供记录的 my_field
数组中的第二项,其中包含 _id
、id
.>
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}
])
以上逻辑不能应用于更多的记录,因为它会涉及$group
,$unwind
之后的操作符.$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.
这篇关于获取数组中的第一个元素并使用聚合返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!