【问题标题】:Multiple insert into mongodb - only the first collection gets updated多次插入 mongodb - 只有第一个集合被更新
【发布时间】:2018-10-24 08:31:03
【问题描述】:

我正在尝试更新我在 mlab 上托管的 mongodb 实例中的集合。

我正在运行以下代码:

...
db.collectionOne.insert(someArrayOfJson)
db.collectionTwo.insert(someArrayOfJson)

第一个集合得到更新,而第二个没有。

使用相同/不同的有效 Json 数组会产生相同的结果。只有第一个得到更新。

我已经看到了这个问题duplicate document - same collection,我可以理解为什么它不起作用。但我的问题是跨两个单独的集合?

当在 mlab 上手动插入数据时,文档会进入第二个集合 - 所以我相信它允许跨单独集合重复数据。

我是 mongo 的新手 - 我错过了一些简单的东西吗?

更新:

回复是:

22:01:53.224 [main] DEBUG org.mongodb.driver.protocol.insert - Inserting 20 documents into namespace db.collectionTwo on connection [connectionId{localValue:2, serverValue:41122}] to server ds141043.mlab.com:41043
22:01:53.386 [main] DEBUG org.mongodb.driver.protocol.insert - Insert completed
22:01:53.403 [main] DEBUG org.mongodb.driver.protocol.insert - Inserting 20 documents into namespace db.collectionOne on connection [connectionId{localValue:2, serverValue:41122}] to server ds141043.mlab.com:41043
22:01:55.297 [main] DEBUG org.mongodb.driver.protocol.insert - Insert completed

但是第二个数据集的数据库中没有输入任何内容。

更新 v2:

如果我在两次插入之后拨打电话,例如:

db.createCollection("log", { capped : true, size : 5242880, max : 5000 } )

数据集合得到更新!

【问题讨论】:

  • 您是否将此作为交易的一部分?两个集合都存在吗?两个集合的唯一键/索引是什么?您对文档数组使用相同还是不同的变量?
  • 不是交易的一部分。索引是不同的(在调用之前删除集合 - 插入重新创建它们)。有趣的是,如果我在第二次调用后用新名称调用 db.createcollection,则两个集合都会更新
  • 我已经用与上述相关的信息更新了问题。
  • let x1 = [{name:'a'}, {name:'b'}]; let x2 = [{name:'c'}, {name:'d'}]; 然后 db.one.insert(x1); db.two.insert(x2) 在 shell 中运行非常适合我使用 mongo v4 和干净的数据库。也许这个例子可以帮助你理解你的情况
  • @JohnM 这也发生在本地 MongoDB 部署中,还是仅在 mLab 上?

标签: database mongodb groovy mlab gmongo


【解决方案1】:

什么是总数据大小???

这是适用于我的示例代码

db.collectionOne.insert([{"name1":"John","age1":30,"cars1":[ "Ford", "BMW", "Fiat"]},{"name1":"John","age1":30,"cars1":[ "Ford", "BMW", "Fiat" ]}]); db.collectionTwo.insert([{"name2":"John","age2":30,"cars2":[ "Ford", "BMW", "Fiat"]},{"name2":"John","age2":30,"cars2":[ "Ford", "BMW", "Fiat" ]}])

如果数据更多,您可以使用“Mongo Bulk Write Operations”,也可以参考 Mongo DB 限制和阈值

https://docs.mongodb.com/manual/reference/limits

【讨论】:

    【解决方案2】:

    您是如何确定第二个集合没有更新的?

    我相信您只是看到了 NoSQL 和 SQL 数据库之间的区别。 SQL 数据库将保证您在成功写入后的读取将读取您刚刚写入的数据。 NoSQL 数据库不保证您可以立即读取刚刚写入的数据。请参阅this answer 了解更多详细信息。

    【讨论】:

    • "您如何确定第二个集合没有更新?" - 我登录 Mlab 并检查
    • @JohnM 你的程序是用什么语言编写的?您将其标记为groovy,但groovy 应该使用Java MongoDB 驱动程序,该驱动程序使用insertOne()insertMany() 而不是insert()。如果将文档插入 3 个集合中,会发生什么?如果您使用多数人的写关注,日志记录会发生什么?
    • 使用 Gmongo : github.com/poiati/gmongo - 但这只是一个包装器
    • @JohnM Gmongo 非常旧且不受支持,您看到的行为可能是由于 MongoDB 写入的异步性质存在某种问题,并且可能与过时的 Java 驱动程序不兼容使用。根据我的阅读,Gmongo 使用的是 2.13.0 版本的 MongoDB Java 驱动程序,而支持的最旧版本是 2.13.3,当前版本是 3.8.2。我强烈建议转储 Gmongo 并直接使用 the latest Java driver
    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2011-09-24
    • 2020-07-17
    • 2021-07-04
    • 1970-01-01
    相关资源
    最近更新 更多