Ana*_*via 5 mongodb mongodb-query
根据这个答案,我试图找出数组的大小并将其保存在额外的字段中。
我有一个集合user_details,文档结构类似于:
{
user_id : 1,
likes : [1,2,3,4],
likes_count : 0
}
Run Code Online (Sandbox Code Playgroud)
我正在使用的查询如下:
db.user_details.update({user_id : 1},{$set:{ likes_count : this.likes.length }})
Run Code Online (Sandbox Code Playgroud)
但是,它会抛出错误
"message" : "Cannot read property 'length' of undefined"
Run Code Online (Sandbox Code Playgroud)
如何在额外字段中保存数组的长度?
PS:我使用的是 MongoDB 3.4
https://docs.mongodb.com/manual/reference/operator/aggregation/size/#exp._S_size
db.users.aggregate(
[
{
$project: {
likes_count: { $size: "$test" }
}
}
]
)
Run Code Online (Sandbox Code Playgroud)
将返回的结果存储likes_count在 an 中variable并通过提供likes_count变量来执行更新
像这样的东西
Model.aggregate(
[
{
$project: {
likes_count: { $size: "$test" }
}
}
], (err, re) => {
console.log(err, re);
var likes_count = re[0].likes_count;
Model.update({email: 1}, {$set: {likes_count: likes_count}}, (err, d) => {
console.log(err, d);
})
}
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4881 次 |
| 最近记录: |