有没有办法在不循环所有项目的情况下将所有项目集合复制到新集合? 我找到了一种通过 DBCursor 循环的方法:
...
DB db = mongoTemplate.getDb();
DBCursor cursor = db.getCollection("xxx").find();
//loop all items in collection
while (cursor.hasNext()) {
BasicDBObject b = (BasicDBObject) cursor.next();
// copy to new collection
service.createNewCollection(b);
}
...
你能建议在 java 中复制而不循环所有项目吗?
(不在 mongo shell 中,使用 java 实现)
谢谢。
最佳答案
在 MongoDB 2.6 中,$out aggregation operator添加了将聚合结果写入集合的方法。这提供了一种使用 Java 驱动程序(我使用 Java 驱动程序版本 2.12.0)将一个集合中的所有项目在服务器端复制到同一数据库中的另一个集合的简单方法:
// set up pipeline
List<DBObject> ops = new ArrayList<DBObject>();
ops.add(new BasicDBObject("$out", "target")); // writes to collection "target"
// run it
MongoClient client = new MongoClient("host");
DBCollection source = client.getDB("db").getCollection("source")
source.aggregate(ops);
单行版本:
source.aggregate(Arrays.asList((DBObject)new BasicDBObject("$out", "target")));
根据文档,对于大型数据集 (>100MB),您可能需要使用 allowDiskUse 选项 ( Aggregation Memory Restrictions ),尽管我在 >2GB 的集合上运行它时没有遇到该限制,所以它可能不适用于这个特定的管道,至少在 2.6.0 中是这样。
关于java - MongoDB - 在 java 中复制集合而不循环所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16164413/