当前位置: 首页>>代码示例>>Java>>正文


Java MongoCollection.updateOne方法代码示例

本文整理汇总了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);
	}
}
 
开发者ID:sundarcse1216,项目名称:mongodb-crud,代码行数:23,代码来源:UpdateDocumentsImpl.java

示例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
    }
}
 
开发者ID:jython234,项目名称:nectar-server,代码行数:28,代码来源:FTSController.java

示例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;
	}

}
 
开发者ID:dianbaer,项目名称:grain,代码行数:30,代码来源:MongodbManager.java

示例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);
	}
}
 
开发者ID:sundarcse1216,项目名称:mongodb-crud,代码行数:22,代码来源:UpdateDocumentsImpl.java

示例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())));
}
 
开发者ID:jython234,项目名称:nectar-server,代码行数:9,代码来源:ClientSession.java

示例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;
}
 
开发者ID:jiumao-org,项目名称:wechat-mall,代码行数:10,代码来源:MongoCRUD.java

示例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;
}
 
开发者ID:breakEval13,项目名称:rocketmq-flink-plugin,代码行数:37,代码来源:MongoManager.java

示例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;
}
 
开发者ID:breakEval13,项目名称:rocketmq-flink-plugin,代码行数:37,代码来源:MongoManager.java

示例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.");
}
 
开发者ID:jython234,项目名称:nectar-server,代码行数:68,代码来源:AuthController.java

示例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.");
}
 
开发者ID:jython234,项目名称:nectar-server,代码行数:44,代码来源:AuthController.java

示例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;
}
 
开发者ID:Superioz,项目名称:MooProject,代码行数:5,代码来源:DatabaseConnection.java

示例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);
}
 
开发者ID:wxz1211,项目名称:dooo,代码行数:15,代码来源:MongodbDataAccess.java


注:本文中的com.mongodb.client.MongoCollection.updateOne方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。