MongoDB:更新和子文档

编程入门 行业动态 更新时间:2024-10-17 21:23:48
本文介绍了MongoDB:更新和子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们假设以下架构:

{ '_id' : 'star_wars', 'count' : 1234, 'spellings' : [ { spelling: 'Star wars', total: 10}, { spelling: 'Star Wars', total : 15}, { spelling: 'sTaR WaRs', total : 5} ] }

我可以通过这样做来更新计数和拼写之一:

I can update the count and one of the spellings by doing this:

db.movies.update( {_id: "star_wars", 'spellings.spelling' : "Star Wars" }, { $inc : { 'spellings.$.total' : 1, 'count' : 1 }} )

但是这种形式的更新不适用于 upsert.即,如果我尝试使用不存在的 _id 或拼写不存在的 _id 进行更新(使用 upsert),则不会发生任何事情.

But this form of update doesn't work with upsert. i.e., if I try to update (with upsert) with an _id that doesn't exist, or with a spelling that doesn't already exist, nothing happens.

有没有一种解决方案可以让我在更新 ($inc) 子文档时进行 upsert?

Is there a solution that allows me to upsert when updating ($inc) a sub-document?

谢谢!

推荐答案

不过,您可以稍微更改一下架构.如果您的文档如下所示:

You could change your schema a little, though. If your documents looked like this:

{ '_id' : 'star_wars', 'count' : 1234, 'spellings' : { 'Star wars': 10, 'Star Wars': 15, 'sTaR WaRs': 5 } }

您的更新将变得如此简单:

Your updates would become as simple as:

db.movies.update({_id:"star_wars"},{$inc:{"spellings.Star Wars":1}},true)

更多推荐

MongoDB:更新和子文档

本文发布于:2023-11-22 13:40:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:新和   文档   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!