gpt4 book ai didi

mongodb - 将数组中的第一项投影到新字段(MongoDB 聚合)

转载 作者:IT老高 更新时间:2023-10-28 13:03:55 25 4
gpt4 key购买 nike

我正在使用 Mongoose 聚合(MongoDB 3.2 版)。

我有一个字段 users 这是一个数组。我想 $project 将此数组中的第一项添加到新字段 user

我试过了

  { $project: {
user: '$users[0]',
otherField: 1
}},

{ $project: {
user: '$users.0',
otherField: 1
}},

{ $project: {
user: { $first: '$users'},
otherField: 1
}},

但两者都不起作用。

我怎样才能正确地做到这一点?谢谢

最佳答案

更新:

从 v4.4 开始,有一个专门的运算符 $first :

{ $project: {
user: { $first: "$users" },
otherField: 1
}},

这是语法糖

原答案:

您可以使用 arrayElemAt :

{ $project: {
user: { $arrayElemAt: [ "$users", 0 ] },
otherField: 1
}},

关于mongodb - 将数组中的第一项投影到新字段(MongoDB 聚合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39196537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com