如解释here ,将一组新文档批量插入到 MongoDB 集合中相当容易:
batch = [{:name => "mongodb"}, {:name => "mongoid"}]
Article.collection.insert(batch)
但我觉得不容易的是如何检索新创建的 ID 列表。是否可以编写如下代码:
batch = [{:name => "mongodb"}, {:name => "mongoid"}]
result = Article.collection.insert(batch)
result[:ids] # not real code
提前致谢!
最佳答案
您现在可以使用 inserted_ids https://www.mongodb.com/docs/ruby-driver/master/api/Mongo/BulkWrite/Result.html 访问此数据所以对于你的例子就是
batch = [{:name => "mongodb"}, {:name => "mongoid"}]
result = Article.collection.insert_many(batch)
result.inserted_ids
关于ruby-on-rails - Mongoid 批量收集插入 : how to get the ids of the newly created items?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27839205/