在 MongoDB 文档中插入匹配条件的数组元素? [英] Upsert Array Elements matching criteria in a MongoDB document?

查看:29
本文介绍了在 MongoDB 文档中插入匹配条件的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 我该怎么做更新 MongoDB 文档中匹配条件的数组元素?

我想向上插入数组元素,所以如果不匹配则插入它,否则更新它.

I want to upsert the array elements, so if one doesnt match then insert it, otherwise update it.

我尝试了该问题的答案,如果数组元素已经存在,它可以正常工作.如果该元素不存在,则在数组字段下创建$"的子元素.

I tried the answer on that question, and it works fine IF the array element already exists. If the element doesnt exist then it creates a child of "$" under the array field.

我的Mongo结构如下:

My Mongo structure is as follows:

Widget (collection)
--Name
--Properties (array)
  --Name
  --Value

我的应用程序从 WebService 调用获取小部件名称和属性列表.如果名称已经存在,我希望迭代提供的属性并更新 MongoDB 中的值,或者如果不存在,则向 Properties 数组插入一个新属性.

My application gets a Widget Name and a list of Properties from a WebService call. I wish to iterate the provided Properties and update the value in the MongoDB if the Name already exists, OR insert a new Property to the Properties array if it doesnt.

推荐答案

如果没有一些应用程序端逻辑,使用单个更新是不可能满足您的需求的.请注意,作为一项功能的 upsert 与此特定问题无关,除非您想在不存在具有提供名称的 Widget 文档的情况下自动创建新的 Widget 文档.

What you require is not possible using a single update without some app-side logic. Note that upsert as a feature is not relevant for this specific problem unless you want to automatically create new Widget documents if none exist with the provided name.

您遇到的问题是,没有任何功能允许您根据数组元素的存在进行两种不同的更新.您仅有的两个选择是:

The problem you're running into is that there is no functionality that allows you to do two different updates depending on the existence of an array element. Your only two options are :

  1. 找到该项目,确定相关属性是否存在,使用您的新属性或更改属性编译适当的更新并执行它.这带来了一个重要的缺点,即这不是一种并发安全的方法.换句话说,如果两个 Web 服务同时尝试此操作,则可能会覆盖彼此的更改.
  2. 使小部件属性成为顶级文档,而不是嵌入.允许您使用 upserts 做您想做的事.明显的缺点是,就架构设计而言,这不是一个很好的选择.例如,如果您获取一个小部件,您将不会自动获取所有属性.

这篇关于在 MongoDB 文档中插入匹配条件的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆