你好我有簡單的收藏:
{
_id: 1,
books: [
{ bookId: 55, c: 5},
{ bookId: 66, c: 6},
{ bookId: 77, c: 7},
]
}
我如何通過計算其他欄位來添加新欄位?在這里,我通過計算欄位“C”將欄位“Z”添加到嵌套陣列中當前找到的物件
updateOne(
{
_id : 1,
'books.bookId' : 66
} ,
{
[
{ $addFields: { "books.$.z" : { "$sum" : ["$books.$.c", 1] } } }
]
}
預期結果:
{
_id: 1,
books: [
{ bookId: 55, c: 5},
{ bookId: 66, c: 6, z:7},
{ bookId: 77, c: 7},
]
}
我認為有一個簡短的條目(可能使用新的 $getField ?!),我認為 mango 仍然能夠結合 'position operator $' ('variable operator reference by prefix $' 或 'combine with $getField') 我如何試試我的樣本
uj5u.com熱心網友回復:
在 update 方法中使用聚合管道來利用運算子$map,$mergeObjects并$cond達到預期的結果:
.updateOne(
// The query will find docs where *at least* one bookId in the
// books array equals 66 -- but remember it does not pinpoint
// the location in the array! We will tackle that in the update
// pipeline to follow...
{ _id: 1, 'books.bookId': 66 },
[
{ $set: {
books: {
$map: {
input: '$books',
in: {
$mergeObjects: [
'$$this',
{
$cond: [
{ $eq: ['$$this.bookId', 66] }, // IF books.bookId == 66
{ z: { $sum: ['$$this.c', 1] } }, // THEN merge a new field 'z' with calced value
null // ELSE merge null (a noop)
]
}
]
}
}
}
} }
]
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/433627.html
標籤:数组 mongodb 猫鼬 mongodb查询 聚合框架
上一篇:聚合與嵌套值的組和總和
