如何更新MongoDB嵌套数组posts内指定_id对应post的likes数组?
解决方案
你可以使用MongoDB的数组位置操作符$实现需求,$会自动匹配查询条件中命中的posts数组元素下标,仅更新对应post的likes数组,以下分两种常用场景提供语句:
场景1:添加userId到likes数组
推荐使用$addToSet避免同一用户重复点赞,若需要允许重复添加可替换为$push:
// 替换为实际参数,此处假设集合名为users const targetPostId = ObjectId("替换为目标post的_id"); const toAddUserId = ObjectId("替换为要添加的userId"); db.users.updateOne( // 查询条件:匹配包含目标post的文档 { "posts._id": targetPostId }, // 更新操作:仅修改命中的post的likes数组 { $addToSet: { "posts.$.likes": toAddUserId } } )
场景2:从likes数组移除指定userId
使用$pull操作符实现:
const targetPostId = ObjectId("替换为目标post的_id"); const toRemoveUserId = ObjectId("替换为要移除的userId"); db.users.updateOne( { "posts._id": targetPostId }, { $pull: { "posts.$.likes": toRemoveUserId } } )
注意事项
如果使用mongoose等ODM工具,不需要手动封装ObjectId,传入符合格式的id字符串即可自动转换,也可通过对应ODM提供的ObjectId方法手动转换类型。
内容的提问来源于stack exchange,提问作者Vishnu Mohan
相关产品推荐
相关产品推荐

