将数组中的第一项投影到新字段(MongoDB 聚合) [英] Project first item in an array to new field (MongoDB aggregation)
本文介绍了将数组中的第一项投影到新字段(MongoDB 聚合)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用的是 Mongoose 聚合(MongoDB 3.2 版).
I am using Mongoose aggregation (MongoDB version 3.2).
我有一个字段 users
这是一个数组.我想将这个数组中的第一项 $project
放到一个新字段 user
中.
I have a field users
which is an array. I want to $project
first item in this array to a new field user
.
我试过了
{ $project: {
user: '$users[0]',
otherField: 1
}},
{ $project: {
user: '$users.0',
otherField: 1
}},
{ $project: {
user: { $first: '$users'},
otherField: 1
}},
但两者都不起作用.
我该怎么做才能正确?谢谢
How can I do it correctly? Thanks
推荐答案
更新:
从 v4.4 开始有一个专用的操作符 $first:
Starting from v4.4 there is a dedicated operator $first:
{ $project: {
user: { $first: "$users" },
otherField: 1
}},
这是一个语法糖
原答案:
您可以使用arrayElemAt:
{ $project: {
user: { $arrayElemAt: [ "$users", 0 ] },
otherField: 1
}},
这篇关于将数组中的第一项投影到新字段(MongoDB 聚合)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文