且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取数组中的第一个元素并使用Aggregate返回?

更新时间:2023-02-19 11:30:51

当前,$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("...");

然后,下面的聚合命令为您提供带有_idid的记录的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.