mongodb中的异构批量更新 [英] heterogeneous bulk update in mongodb

查看:94
本文介绍了mongodb中的异构批量更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用以下方式批量更新mongodb中的文档

I know that we can bulk update documents in mongodb with

db.collection.update( criteria, objNew, upsert, multi )

在一个数据库调用中,但它是同质的,即所有受影响的文档都遵循一种标准.但是我想做的是类似的

in one db call, but it's homogeneous, i.e. all those documents impacted are following one kind of criteria. But what I'd like to do is something like

db.collection.update([{criteria1, objNew1}, {criteria2, objNew2}, ...]

,发送多个更新请求,这将在单个db调用中更新可能完全不同的文档或文档类.

, to send multiple update request which would update maybe absolutely different documents or class of documents in single db call.

我要在我的应用程序中执行的操作是使用复合主键插入/更新一堆对象,如果该键已经存在,请对其进行更新;否则插入它.

What I want to do in my app is to insert/update a bunch of objects with compound primary key, if the key is already existing, update it; insert it otherwise.

我可以在mongodb中将所有这些组合在一起吗?

Can I do all these in one combine in mongodb?

推荐答案

这是两个单独的问题.到第一个;没有MongoDB本机机制来批量发送条件/更新对,尽管从技术上讲,您这样做在循环中注定要和本机批量支持一样高效.

That's two seperate questions. To the first one; there is no MongoDB native mechanism to bulk send criteria/update pairs although technically doing that in a loop yourself is bound to be about as efficient as any native bulk support.

检查基于嵌入式文档的文档是否存在(您称为复合键,但是为了避免混淆,为了正确使用术语,最好在这种情况下使用mongo名称),然后根据需要插入/更新可以通过upsert来检查存在性:

Checking for the existence of a document based on an embedded document (what you refer to as compound key, but in the interest of correct terminology to avoid confusion it's better to use the mongo name in this case) and insert/update depending on that existence check can be done with upsert :

文档A:

{
    _id: ObjectId(...),
    key: {
        name: "Will",
        age: 20
    }
}

db.users.update({name:"Will", age:20}, {$set:{age: 21}}), true, false)

此upsert(如果没有文档符合条件,则使用insert更新)将根据文档A的存在执行以下两项操作之一:

This upsert (update with insert if no document matches the criteria) will do one of two things depending on the existence of document A :

  • 存在:对现有文档执行更新"$ set:{age:21}"
  • 不存在:使用字段名称"和字段创建新文档 年龄"的值分别为威尔"和"20"(基本上是 条件被复制到新文档中),然后应用更新 ($ set:{age:21}).最终结果是一个文档,其名称为"name" ="Will", "age" = 21.
  • Exists : Performs update "$set:{age:21}" on the existing document
  • Doesn't exist : Create a new document with fields "name" and field "age" with values "Will" and "20" respectively (basically the criteria are copied into the new doc) and then the update is applied ($set:{age:21}). End result is a document with "name"="Will" and "age"=21.

希望有帮助

这篇关于mongodb中的异构批量更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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