本文整理匯總了Java中com.mongodb.client.MongoCollection.updateOne方法的典型用法代碼示例。如果您正苦於以下問題:Java MongoCollection.updateOne方法的具體用法?Java MongoCollection.updateOne怎麽用?Java MongoCollection.updateOne使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類com.mongodb.client.MongoCollection
的用法示例。
在下文中一共展示了MongoCollection.updateOne方法的12個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: updateDocumentWithCurrentDate
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
* This method update document with lastmodified properties
*/
@Override
public void updateDocumentWithCurrentDate() {
MongoDatabase db = null;
MongoCollection collection = null;
Bson filter = null;
Bson query = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
filter = eq("name", "Sundar");
query = combine(set("age", 23), set("gender", "Male"),
currentDate("lastModified"));
UpdateResult result = collection.updateOne(filter, query);
log.info("Update with date Status : " + result.wasAcknowledged());
log.info("No of Record Modified : " + result.getModifiedCount());
} catch (MongoException e) {
log.error("Exception occurred while update Many Document with Date : " + e, e);
}
}
示例2: buildChecksumFile
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
private static void buildChecksumFile(File file, MongoCollection<Document> index, List<Document> toInsert, boolean isPublic) throws IOException {
// Is a file, build the checksum then
String checksum = Util.computeFileSHA256Checksum(file);
Document fileDoc = index.find(Filters.eq("path", file.getAbsolutePath())).first();
if(fileDoc == null) {
toInsert.add(new Document()
.append("path", file.getAbsolutePath())
.append("storePath", Util.absoluteFTSToRelativeStore(file.getAbsolutePath()))
.append("isPublic", isPublic)
.append("checksum", checksum)
.append("lastUpdatedBy", "server"));
} else {
String dbChecksum = fileDoc.getString("checksum");
if(!checksum.equals(dbChecksum)) {
// Checksum has changed, we assume the file has been changed by the server
// This is because if a client changes it, the database will be updated
index.updateOne(Filters.eq("path", file.getAbsolutePath()),
new Document("$set", new Document("checksum", checksum))
); // Update the checksum into the database
index.updateOne(Filters.eq("path", file.getAbsolutePath()),
new Document("$set", new Document("lastUpdatedBy", "server"))
); // Change lastUpdatedBy to "server"
}
// else: Checksum has not changed, all is well
}
}
示例3: updateById
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
* 修改記錄
*
* @param collectionName
* 表名
* @param mongoObj
* 對象
* @return
*/
public static boolean updateById(String collectionName, MongoObj mongoObj) {
MongoCollection<Document> collection = getCollection(collectionName);
try {
Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
mongoObj.setDocument(null);
Document document = objectToDocument(mongoObj);
UpdateResult result = collection.updateOne(filter, new Document(MongoConfig.$SET, document));
if (result.getMatchedCount() == 1) {
return true;
} else {
return false;
}
} catch (Exception e) {
if (log != null) {
log.error("修改記錄失敗", e);
}
return false;
}
}
示例4: updateOneDocument
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
* This method update only one one document which is matched first
*/
@Override
public void updateOneDocument() {
MongoDatabase db = null;
MongoCollection collection = null;
Bson filter = null;
Bson query = null;
try {
db = client.getDatabase(mongo.getDataBase());
collection = db.getCollection(mongo.getSampleCollection());
filter = eq("name", "Sundar");
query = combine(set("age", 23), set("gender", "Male"));
UpdateResult result = collection.updateOne(filter, query);
log.info("UpdateOne Status : " + result.wasAcknowledged());
log.info("No of Record Modified : " + result.getModifiedCount());
} catch (MongoException e) {
log.error("Exception occurred while update single Document : " + e, e);
}
}
示例5: updateState
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
public void updateState(ClientState state) {
NectarServerApplication.getLogger().info("Client " + token.getUuid() + " state updated to: " + state.toString());
this.state = state;
MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
clients.updateOne(Filters.eq("uuid", token.getUuid()),
new Document("$set", new Document("state", state.toInt())));
}
示例6: updateById
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
public static Document updateById(MongoCollection<Document> col, Object id, Document newDoc,
boolean repalce) {
Bson filter = Filters.eq("_id", id);
if (repalce)
col.replaceOne(filter, newDoc);
else
col.updateOne(filter, new Document("$set", newDoc));
return newDoc;
}
示例7: executeUpdate
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
* @param dbName 庫名
* @param collectionName 表名
* @param json1 條件
* @param json2 保存doc
* @return 更新結果信息
*/
public JSONObject executeUpdate(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
JSONObject resp = new JSONObject();
try {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
JSONObject saveJson = new JSONObject();
saveJson.put("$set", json2);
Document doc1 = Document.parse(json1.toString());
Document doc2 = Document.parse(saveJson.toString());
UpdateResult ur = coll.updateOne(doc1, doc2);
System.out.println("doc1 = " + doc1.toString());
System.out.println("doc2 = " + doc2.toString());
if (ur.isModifiedCountAvailable()) {
if (json1.containsKey(ID)) {
resp.put("Data", json1.get(ID));
} else {
resp.put("Data", json1);
}
}
} catch (MongoTimeoutException e1) {
e1.printStackTrace();
resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
return resp;
} catch (Exception e) {
e.printStackTrace();
resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
}
return resp;
}
示例8: executeUpsert
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
* @param dbName 庫名
* @param collectionName 集合名
* @param json1 條件
* @param json2 保存doc
* @return upsert結果信息
*/
public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
JSONObject resp = new JSONObject();
try {
MongoDatabase db = mongoClient.getDatabase(dbName);
MongoCollection coll = db.getCollection(collectionName);
JSONObject saveJson = new JSONObject();
saveJson.put("$set", json2);
Document doc1 = Document.parse(json1.toString());
Document doc2 = Document.parse(saveJson.toString());
UpdateOptions up = new UpdateOptions();
up.upsert(true);
UpdateResult ur = coll.updateOne(doc1, doc2, up);
if (ur.isModifiedCountAvailable()) {
if (json1.containsKey(ID)) {
resp.put("Data", json1.get(ID));
} else {
resp.put("Data", json1);
}
}
} catch (MongoTimeoutException e1) {
e1.printStackTrace();
resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
return resp;
} catch (Exception e) {
e.printStackTrace();
resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
}
return resp;
}
示例9: login
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
@RequestMapping(value = NectarServerApplication.ROOT_PATH + "/auth/login", method = RequestMethod.POST)
public ResponseEntity<String> login(@RequestParam(value = "token") String jwtRaw, @RequestParam(value = "user") String username,
@RequestParam(value = "password") String password, HttpServletRequest request) {
ResponseEntity r = Util.verifyJWT(jwtRaw, request);
if(r != null)
return r;
SessionToken token = SessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
if(token == null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");
if(SessionController.getInstance().checkToken(token)) {
MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
MongoCollection<Document> users = NectarServerApplication.getDb().getCollection("users");
Document clientDoc = clients.find(Filters.eq("uuid", token.getUuid())).first();
if(clientDoc == null) {
NectarServerApplication.getLogger().warn("Failed to find Client Entry in database for " + token.getUuid());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to find entry in database for client.");
}
String loggedInUser;
try {
// getString will throw an exception if the key is not present in the document
loggedInUser = clientDoc.getString("loggedInUser");
if(loggedInUser.equals("none")) {
// No user is logged in
throw new RuntimeException(); // Move to catch block
}
NectarServerApplication.getLogger().warn("Attempted duplicate user login to already logged in client: " + token.getUuid());
return ResponseEntity.status(HttpStatus.CONFLICT).body("A User is already logged in under this client!");
} catch(Exception e) {
// No user is logged in
Document userDoc = users.find(Filters.eq("username", username)).first();
if(userDoc == null) {
// The user trying to log in does not exist
NectarServerApplication.getLogger().warn("Attempted user login for \"" + username + "\", from "
+ token.getUuid() + ", user not found in database."
);
NectarServerApplication.getEventLog().addEntry(EventLog.EntryLevel.WARNING, "Attempted user login from non-existent user " + username);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found in database!");
}
// Check their password
if(userDoc.getString("password").equals(Util.computeSHA512(password))) {
// Password check complete, now update the database with the state
clients.updateOne(Filters.eq("uuid", token.getUuid()),
new Document("$set", new Document("loggedInUser", username))
);
NectarServerApplication.getEventLog().logEntry(EventLog.EntryLevel.INFO, "User \"" + username + "\" logged in from " + token.getUuid() + ", traced from " + request.getRemoteAddr());
} else {
NectarServerApplication.getLogger().warn("ATTEMPTED LOGIN TO USER \"" + username + "\": incorrect password from " + token.getUuid() +", address: " + request.getRemoteAddr());
NectarServerApplication.getEventLog().addEntry(EventLog.EntryLevel.WARNING, "Failed login to user " + username + " from " + token.getUuid() + ", traced from " + request.getRemoteAddr());
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Password Incorrect!");
}
}
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Success.");
}
示例10: logout
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
@RequestMapping(NectarServerApplication.ROOT_PATH + "/auth/logout")
public ResponseEntity<String> logout(@RequestParam(value = "token") String jwtRaw, HttpServletRequest request) {
ResponseEntity r = Util.verifyJWT(jwtRaw, request);
if(r != null)
return r;
SessionToken token = SessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
if(token == null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");
if(SessionController.getInstance().checkToken(token)) {
MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
Document clientDoc = clients.find(Filters.eq("uuid", token.getUuid())).first();
if(clientDoc == null) {
NectarServerApplication.getLogger().warn("Failed to find Client Entry in database for " + token.getUuid());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to find entry in database for client.");
}
String loggedInUser;
try {
// getString will throw an exception if the key is not present in the document
loggedInUser = clientDoc.getString("loggedInUser");
if(loggedInUser.equals("none")) {
// No user is logged in
throw new RuntimeException(); // Move to catch block
}
} catch(Exception e) {
return ResponseEntity.badRequest().body("No user is currently logged in!");
}
clients.updateOne(Filters.eq("uuid", token.getUuid()),
new Document("$set", new Document("loggedInUser", "none"))
);
NectarServerApplication.getEventLog().logEntry(EventLog.EntryLevel.INFO, "User \"" + loggedInUser + "\" logged out from " + token.getUuid() + ", traced from " + request.getRemoteAddr());
} else {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
}
return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Success.");
}
示例11: upsertSync
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
public long upsertSync(MongoCollection<Document> collection, Bson filter, Document document) {
UpdateResult result = collection.updateOne(filter, document, new UpdateOptions().upsert(true));
return result.getUpsertedId() == null ? result.getModifiedCount() : 1;
}
示例12: updateOne
import com.mongodb.client.MongoCollection; //導入方法依賴的package包/類
/**
* 更新符合條件的一條記錄
*
* @param collectionName 集合名
* @param query 查詢條件
* @param update 更新設置
* @return
*/
public boolean updateOne(String collectionName, MongodbQuery query, MongodbUpdates update) {
MongoCollection collection = sMongoDatabase.getCollection(collectionName);
UpdateResult updateResult = collection.updateOne(query.getQuery(), update.getUpdates());
return updateResult.getUpsertedId() != null ||
(updateResult.getMatchedCount() > 0 && updateResult.getModifiedCount() > 0);
}