当处理一个 Iterable 对象时,Datastore.save() 的预期行为是什么? [英] What is the intended behavior of Datastore.save() when handed an Iterable of objects?

查看:66
本文介绍了当处理一个 Iterable 对象时,Datastore.save() 的预期行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在调试一个涉及 MongoDB 和两个程序的奇怪情况.

I am debugging a bizarre situation involving MongoDB and two programs.

有问题的 MongoDB 安装最初是空的,是一个玩具部署.

The MongoDB installation in question is initially empty and is a toy deployment.

有两个程序.一种是使用 Morphia.另一个没有.

There are two programs. One uses Morphia. The other does not.

不使用 Morphia 的程序将一条记录插入到 foo-bar 数据库中的 Service 集合中,如下所示:

The non-Morphia-using program inserts a record into a Service collection in a foo-bar database like so:

mongo << EOF
db.getSiblingDB("foo-bar").getCollection("Service").replaceOne( {
  "service_name" : "argle-bargle"
}, {
  "_id" : "argle-bargle",
  "className" : "com.foo.Service",
  "service_name" : "argle-bargle",
}, {
  "upsert" : true
} )
EOF

写入被确认:

MongoDB shell version v3.4.6
connecting to: mongodb://aura-mongodb:27017/
MongoDB server version: 3.4.6
{
    "acknowledged" : true,
    "matchedCount" : 0,
    "modifiedCount" : 0,
    "upsertedId" : "argle-bargle"
}
bye

使用 Morphia 的程序执行此操作:

The Morphia-using program does this:

final MongoClient client = // ...
final Morphia morphia = new Morphia();
morphia.mapPackage("com.foo");
final Datastore dataStore = morphia.createDatastore(client, "foo-bar");
assert dataStore != null;
dataStore.ensureIndexes();

……其次是:

final Collection<com.foo.Service> services = // ...collection of size 2...
this.dataStore.save(services);

现在数据库中应该有三个项目.没有.

There should now be three items in the database. There are not.

连接 mongo 并获取 foo-bar 数据库中的 Service 集合并发出 find()显示有两个(使用 Morphia 的程序运行的结果).

Connecting with mongo and getting ahold of the Service collection in the foo-bar database and issuing find() shows there to be two (the result of the Morphia-using program's operation).

我希望如果我在该集合中有 20,000 条记录,save(collectionOf2Items) 不会删除其中的 19,998 条!

I HOPE that if I had 20,000 records in that collection that a save(collectionOf2Items) would not delete 19,998 of them!

那么:当使用 Iterable 时,save 是否具有破坏性?非常感谢有关如何调试这个令人困惑的问题的任何其他建议.

So then: is save destructive when handed an Iterable? Any other suggestions on how to debug this baffling problem are greatly appreciated.

推荐答案

没有任何代码很难判断,但如果项目的 ID 匹配,调用 save() 将简单地更新现有项目.

Hard to tell without any code but if the ID's of the items match calling save() will simply update the existing item.

来自 Morhpia 快速导览

更新 MongoDB 中的数据就像更新 Java 对象然后再次使用它们调用 datastore.save() 一样简单.

Updating data in MongoDB is as simple as updating your Java objects and then calling datastore.save() with them again.

对于调试,尝试手动将 ID 字段设置为您知道尚未使用的 ID 可能是值得的.

For debugging it might be worthwhile to try manually setting the ID fields to an ID you know is not already in use.

这篇关于当处理一个 Iterable 对象时,Datastore.save() 的预期行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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