MongoDB-如何使用另一个集合中的字段向一个集合中的嵌套对象添加字段?

时间:2019-02-26 13:57:59

标签: mongodb nosql aggregation

我有两个集合A和B。

集合A有一个嵌套对象“ nested”,其中有一个字段“ id”。 集合B还具有一个字段“ id”和另一个“类型”。

我的问题是:

如何将集合B的“类型”字段添加到ID匹配的集合A的嵌套对象中?

1 个答案:

答案 0 :(得分:0)

最初,我正在寻找一个神奇的mongo单线查询来完成这项工作,但我想我会充分利用这个想法!

最后,我使用了以下Java解决方案:

 private void updateNestedInCollectionAWithTypeFromCollectionBWhereIdsMatch(List<CollectionBPojo> collectionB, MongoCollection<Document> collectionA) {

    StreamUtils.createStreamFromIterator(collectionA.find().iterator()).forEach(d -> {
        final List<Document> nestedList = (List<Document>)d.get("nested");
        for (int i = 0; i < nestedList.size(); i++) {
            final Document nested = nestedList.get(i);
            if(!nested.containsKey("type")) {
                final String id = nested.getString("id");
                final Optional<CollectionBPojo> collectionBPojo = collectionB.stream().filter(g -> g.getId().equals(id)).findFirst();
                if (collectionBPojo.isPresent()) {
                    final String type = collectionBPojo.get().getType();                 
                    final Document query = new Document("id", d.get("id"));
                    final Document update = new Document();
                    update.append("$set", new BasicDBObject("nested" + "." + i + ".type", type));
                    updates.add(new UpdateOneModel<>(query, update));
                }
            }
        }
    });

    if(!updates.isEmpty()) {
        final BulkWriteResult result = pipelineRunsCollection.bulkWrite(updates);         
    } else {
        System.out.print.ln("Nothing to update on db: " +  db.getName());
    }
}

}

相关问题