假设有一个具有以下文档的收集客户端:
[
{
"id": 1,
"Name": "Susie",
"ownership" : {
"ownershipContextCode" : "C1"
},
"clientIds": [
{
"clientClusterCode": "clientClusterCode_1",
"clientId": "11"
}
]
},
{
"id": 2,
"Name": "John",
"ownership" : {
"ownershipContextCode" : "C2"
},
"clientIds": [
{
"clientClusterCode": "clientClusterCode_2",
"clientId": "22"
}
]
}
]
我尝试将字段(ownershipClientCode)设置为clientIds数组的第一个元素。结果应该如下所示:
[
{
"id": 1,
"Name": "Susie",
"ownership" : {
"ownershipContextCode" : "C1",
"ownershipClientCode" : "clientClusterCode_1"
},
"clientIds": [
{
"clientClusterCode": "clientClusterCode_1",
"clientId": "11"
}
],
},
{
"id": 2,
"Name": "John",
"ownership" : {
"ownershipContextCode" : "C2",
"ownershipClientCode" : "clientClusterCode_2"
},
"clientIds": [
{
"clientClusterCode": "clientClusterCode_2",
"clientId": "22"
}
],
}
]
我正在使用此查询,但无法从数组中的第一个元素获取子对象
db.collection.aggregate([
{
$addFields: {
"Last Semester": {
"$arrayElemAt": [
"$clientIds",
0
]
}
}
}
])
此查询添加all对象,但我只需要字段(clientClusterCode)。
诸如此类的事情
db.collection.aggregate([
{
$addFields: {
"Last Semester": {
"$arrayElemAt": [
"$clientIds",
0
].clientClusterCode
}
}
}
])
我使用的是mongodb 4.0.0
1条答案
按热度按时间nxowjjhe1#
你很接近了:https://mongoplayground.net/p/HY1Pj0P4z12
您可以在
$arrayElemAt
中使用点标记法,也可以在定义字段名称时使用点标记法。要直接设置字段,请执行类似以下操作(在更新中使用聚合):https://mongoplayground.net/p/js-usEJSH_A
注意:
update
的第二个方法需要是数组,这样它才能起到管道的作用。