Java Code Examples for com.mongodb.client.MongoCollection.updateOne()

The following are Jave code examples for showing how to use updateOne() of the com.mongodb.client.MongoCollection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: mongodb-crud   File: UpdateDocumentsImpl.java   View Source Code Vote up 8 votes
/**
 * 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);
	}
}
 
Example 2
Project: nectar-server   File: FTSController.java   View Source Code Vote up 6 votes
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
    }
}
 
Example 3
Project: grain   File: MongodbManager.java   View Source Code Vote up 6 votes
/**
 * 修改记录
 * 
 * @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;
	}

}
 
Example 4
Project: mongodb-crud   File: UpdateDocumentsImpl.java   View Source Code Vote up 5 votes
/**
 * 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);
	}
}
 
Example 5
Project: nectar-server   File: ClientSession.java   View Source Code Vote up 5 votes
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())));
}
 
Example 6
Project: wechat-mall   File: MongoCRUD.java   View Source Code Vote up 5 votes
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;
}
 
Example 7
Project: rocketmq-flink-plugin   File: MongoManager.java   View Source Code Vote up 5 votes
/**
 * @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;
}
 
Example 8
Project: rocketmq-flink-plugin   File: MongoManager.java   View Source Code Vote up 5 votes
/**
 * @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;
}
 
Example 9
Project: nectar-server   File: AuthController.java   View Source Code Vote up 4 votes
@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.");
}
 
Example 10
Project: nectar-server   File: AuthController.java   View Source Code Vote up 4 votes
@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.");
}
 
Example 11
Project: MooProject   File: DatabaseConnection.java   View Source Code Vote up 4 votes
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;
}
 
Example 12
Project: dooo   File: MongodbDataAccess.java   View Source Code Vote up 3 votes
/**
 * 更新符合条件的一条记录
 *
 * @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);
}