如何使用MongoDB Java更新文档并设置字段的值?

问题描述 投票:0回答:1

在sql中,语句看起来像:UPDATE table SET table.password = pPassword WHERE(table._id = pid);

如何在Java和MongoDB中使用?

function(){
BasicDBObject cBsonFilter = new BasicDBObject();
cBsonFilter.append(COL_id, new BasicDBObject("$eq", pid)); // COL_id = _id // pid = is the right id as String

Document cBsonUpdate = new Document();
cBsonUpdate.put(COL_password, pPassword); // COL_password = password // pPassword ist the password_hash as String

// cMongoDatabase = working connection
User.doFindAndUpdateOne(cMongoDatabase, User.class.getSimpleName(), cBsonFilter, cBsonUpdate);
}

public static UpdateResult doFindAndUpdateOne(MongoDatabase cMongoDatabase, String pNameCollection, BasicDBObject pFilter, Document pUpdate) {
    return cMongoDatabase.getCollection(pNameCollection).updateOne(pFilter, pUpdate);
}

现有:

{
        "_id" : ObjectId("5ed4b1b45c603146a9abc7d2"),
        "Display" : null,
        "Name" : null,
        "birthdate" : null,
        "image" : null,
        "email" : "[email protected]",
        "_lc" : ISODate("2020-06-01T07:44:06.176Z"),
        "lastuserip" : "0:0:0:0:0:0:0:1",
        "userlaw" : 1,
        "validationhash" : null,
        "registered" : ISODate("2020-06-01T07:43:48.843Z"),
        "termsofservice" : null,
        "password" : null
}

收件人:我要输入ID并修改密码。我不想替换整个文档。

{
        "_id" : ObjectId("5ed4b1b45c603146a9abc7d2"),
        "Display" : null,
        "Name" : null,
        "birthdate" : null,
        "image" : null,
        "email" : "[email protected]",
        "_lc" : ISODate("2020-06-01T07:44:06.176Z"),
        "lastuserip" : "0:0:0:0:0:0:0:1",
        "userlaw" : 1,
        "validationhash" : null,
        "registered" : ISODate("2020-06-01T07:43:48.843Z"),
        "termsofservice" : null,
        "password" : passwordhash**************************
}
java mongodb mongodb-java
1个回答
0
投票

解决方案:

Document cDocument = new Document();
cDocument.put(COL_id, pid);

BasicDBObject cUpdate = new BasicDBObject();
cUpdate.append("$set", new BasicDBObject(COL_password, pPassword));
// db.User.updateOne({"_id" : ObjectId("5ed4c1d6e281874721b019c7")}, {$set: {"password": "test"}}, {upsert:true});

User.doFindAndUpdateOne(cMongoDatabase, User.class.getSimpleName(), cDocument, cUpdate);
© www.soinside.com 2019 - 2024. All rights reserved.