有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过Java API将具有值的字段添加到MongoDB中的现有文档中

以下代码对我不起作用:

public void addFieldWithValueToDoc(String DBName, String collName, String docID, String key, String value) {
    BasicDBObject setNewFieldQuery = new BasicDBObject().append("$set", new BasicDBObject().append(key, value));
    mongoClient.getDB(DBName).getCollection(collName).update(new BasicDBObject().append("_id", docID), setNewFieldQuery);
}

其中,mongoClient变量的类型为mongoClient

它的灵感来自Add new field to a collection in MongoDB。 什么是错的,怎么做才是对的? 谢谢


共 (2) 个答案

  1. # 1 楼答案

    我已经编写了一个JUnit测试来证明您的代码确实有效:

    @Test
    public void shouldUpdateAnExistingDocumentWithANewKeyAndValue() {
        // Given
        String docID = "someId";
        collection.save(new BasicDBObject("_id", docID));
        assertThat(collection.find().count(), is(1));
    
        // When
        String key = "newKeyName";
        String value = "newKeyValue";
        addFieldWithValueToDoc(db.getName(), collection.getName(), docID, key, value);
    
        // Then
        assertThat(collection.findOne().get(key).toString(), is(value));
    }
    
    public void addFieldWithValueToDoc(String DBName, String collName, String docID, String key, String value) {
        BasicDBObject setNewFieldQuery = new BasicDBObject().append("$set", new BasicDBObject().append(key, value));
        mongoClient.getDB(DBName).getCollection(collName).update(new BasicDBObject().append("_id", docID), setNewFieldQuery);
    }
    

    因此,您的代码是正确的,尽管我想指出一些关于样式的注释,以使其更具可读性:

    1. 参数和变量应以小写字母开头DBName应该是dbName
    2. 你不需要new BasicDBObject().append(key, value)使用new BasicDBObject(key, value)

    此代码与您的代码具有相同的功能,但更短、更简单:

    public void addFieldWithValueToDoc(String dbName, String collName, String docID, String key, String value) {
        mongoClient.getDB(dbName).getCollection(collName).update(new BasicDBObject("_id", docID),
                                                                 new BasicDBObject("$set", new BasicDBObject(key, value)));
    }
    
  2. # 2 楼答案

    To update existing documents in a collection, you can use the collection’s updateOne() or updateMany methods.

    updateOne方法具有以下form

    db.collection.updateOne(filter, update, options)
    

    filter - the selection criteria for the update. The same query selectors as in the find() method are available.

    Specify an empty document { } to update the first document returned in the collection.

    update - the modifications to apply.

    因此,如果您想使用Mongodb Java driver 3.4+再添加一个字段,它将是:

    collection.updateOne(new Document("flag", true),
                            new Document("$set", new Document("title", "Portable Space Ball")));
    

    以下操作更新单个文档,其中flag:true

    或者按照同样的逻辑:

    collection.updateOne(eq("flag", true),
                                new Document("$set", new Document("title", "Portable Space Ball")));
    

    如果title字段不存在,^{}将添加具有指定值的新字段,前提是新字段不违反类型约束。如果为不存在的字段指定虚线路径,$set将根据需要创建嵌入文档,以实现该字段的虚线路径