本文整理汇总了Java中com.mongodb.client.model.Filters类的典型用法代码示例。如果您正苦于以下问题:Java Filters类的具体用法?Java Filters怎么用?Java Filters使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Filters类属于com.mongodb.client.model包,在下文中一共展示了Filters类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: additionalPropertiesInPojoTest
import com.mongodb.client.model.Filters; //导入依赖的package包/类
@Test
public void additionalPropertiesInPojoTest() {
MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("documents");
MorePropertiesPojo pojo = new MorePropertiesPojo();
pojo.someNonPersistableString = "do not persist me!";
pojo.aString = "persistable String";
pojo.anInt = 22;
// first insert
collection.withDocumentClass(MorePropertiesPojo.class).insertOne(pojo);
// second insert
pojo.id = null;
collection.withDocumentClass(CompletePojo.class).insertOne(pojo);
CompletePojo readPojo = collection.withDocumentClass(CompletePojo.class).find(Filters.eq("_id", pojo.id)).first();
Assert.assertEquals(readPojo.aString, pojo.aString);
}
示例2: getPendingDataLoader
import com.mongodb.client.model.Filters; //导入依赖的package包/类
public O2MSyncDataLoader getPendingDataLoader() {
O2MSyncDataLoader loader = null;
Document document = syncEventDoc.findOneAndUpdate(
Filters.and(Filters.eq(SyncAttrs.STATUS, SyncStatus.PENDING),
Filters.eq(SyncAttrs.EVENT_TYPE, String.valueOf(EventType.System))),
Updates.set(SyncAttrs.STATUS, SyncStatus.IN_PROGRESS),
new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
.projection(Projections.include(SyncAttrs.SOURCE_DB_NAME, SyncAttrs.SOURCE_USER_NAME)));
if (document != null && !document.isEmpty()) {
Object interval = document.get(SyncAttrs.INTERVAL);
String appName = document.getString(SyncAttrs.APPLICATION_NAME);
if(interval!=null && interval instanceof Long){
loader = new O2MSyncDataLoader((Long)interval, appName);
}else{
loader = new O2MSyncDataLoader(120000, appName);
}
loader.setEventId(document.getObjectId(SyncAttrs.ID));
loader.setDbName(document.getString(SyncAttrs.SOURCE_DB_NAME));
loader.setDbUserName(document.getString(SyncAttrs.SOURCE_USER_NAME));
loader.setStatus(document.getString(SyncAttrs.STATUS));
}
return loader;
}
示例3: getFilterBson
import com.mongodb.client.model.Filters; //导入依赖的package包/类
public static Bson getFilterBson(MatchOperator operator , String attributeName , Object value){
Bson filter = null;
switch(operator){
case GT :
filter=Filters.gt(attributeName, value);
break;
case LT :
filter=Filters.lt(attributeName, value);
break;
case GTE :
filter=Filters.gte(attributeName, value);
break;
case LTE :
filter=Filters.lte(attributeName, value);
break;
case EQ :
filter=Filters.eq(attributeName, value);
break;
case NE :
filter=Filters.ne(attributeName, value);
break;
default :
filter=Filters.eq(attributeName, value);
break;
}
return filter;
}
示例4: deleteById
import com.mongodb.client.model.Filters; //导入依赖的package包/类
/**
* 删除记录
*
* @param collectionName
* 表名
* @param mongoObj
* 记录
* @return
*/
public static boolean deleteById(String collectionName, MongoObj mongoObj) {
MongoCollection<Document> collection = getCollection(collectionName);
try {
Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
DeleteResult result = collection.deleteOne(filter);
if (result.getDeletedCount() == 1) {
return true;
} else {
return false;
}
} catch (Exception e) {
if (log != null) {
log.error("删除记录失败", e);
}
return false;
}
}
示例5: doTranslate
import com.mongodb.client.model.Filters; //导入依赖的package包/类
private Map<String, List<String>> doTranslate(Set<String> tokens) {
MongoCollection<Document> lexColl = getLexCollection();
FindIterable<Document> lexs = lexColl.find(Filters.in(TERM_FIELD, tokens));
Map<String, List<String>> res = new HashMap<>();
for (Document doc : lexs) {
Document tr = (Document) doc.get(TRANSLATION_FIELD);
if (tr != null) {
tr.remove(NULL_VALUE);
res.put(doc.getString(TERM_FIELD), getRelevantTranslations((Map) tr));
}
}
return res;
}
示例6: retryEvent
import com.mongodb.client.model.Filters; //导入依赖的package包/类
public SyncEvent retryEvent(ObjectId eventId, boolean retryFailed, boolean retryEntire, boolean dropCollection) {
Document updateQuery = new Document();
updateQuery.append("$set", new Document(SyncAttrs.STATUS, SyncStatus.PENDING).append(SyncAttrs.IS_RETRY, true))
.append("$unset", new Document(SyncAttrs.ERRORS, true).append(SyncAttrs.MARKER, true));
if (retryFailed) {
syncEvents.updateMany(
Filters.and(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId),
Filters.eq(SyncAttrs.STATUS, SyncStatus.FAILED), Filters.ne(SyncAttrs.ID, eventId)),
updateQuery);
syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId),
Updates.set(SyncAttrs.STATUS, SyncStatus.IN_PROGRESS));
} else {
if (retryEntire) {
syncEvents.updateMany(Filters.eq(SyncAttrs.PARENT_EVENT_ID, eventId),
Updates.set(SyncAttrs.STATUS, SyncStatus.CANCELLED));
syncEvents.updateOne(Filters.eq(SyncAttrs.ID, eventId), updateQuery);
}
}
return getEvent(eventId);
}
示例7: main
import com.mongodb.client.model.Filters; //导入依赖的package包/类
public static void main(String[] args) {
MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder().codecRegistry(getCodecRegistry()).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), mongoClientOptions);
MongoDatabase database = mongoClient.getDatabase("tutorial");
MongoCollection<PolymorphicPojo> collection = database.getCollection("entities").withDocumentClass(PolymorphicPojo.class);
// create some pojo
Pojo pojo = new Pojo();
pojo.setName("A nice name");
pojo.setPojos(Arrays.asList(new SubPojo(42), new SubPojo(48)));
// insert into db
collection.insertOne(pojo);
// read from db
PolymorphicPojo foundPojo = collection.find(Filters.eq("_id", pojo.getId())).first();
// output
LOGGER.debug("Found pojo {}", foundPojo);
}
示例8: queryClientState
import com.mongodb.client.model.Filters; //导入依赖的package包/类
/**
* Get the current ClientState of a client,
* connected or not.
* @param uuid The UUID of the client. This must be a valid
* UUID which belongs to a client. If the UUID is
* not found in the database or connected clients,
* then a RuntimeException is thrown.
* @return The ClientState of the specified client with the UUID.
*/
public ClientState queryClientState(String uuid) {
for(ClientSession session : this.sessions.values()) {
if(session.getToken().getUuid().equals(uuid)) {
return session.getState();
}
}
// The session is not currently connected, so we need to check the database
MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
Document doc = clients.find(Filters.eq("uuid", uuid)).first();
if(doc != null) {
return ClientState.fromInt(doc.getInteger("state", ClientState.UNKNOWN.toInt()));
}
// We couldn't find the client in the database, so throw an exception
throw new RuntimeException("Failed to find UUID " + uuid + "in connected sessions or in database. Is it invalid?");
}
示例9: buildChecksumFile
import com.mongodb.client.model.Filters; //导入依赖的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
}
}
示例10: constructIndexJSON
import com.mongodb.client.model.Filters; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private IndexJSON[] constructIndexJSON(MongoCollection<Document> index, boolean isPublic, String loggedInUser) {
List<IndexJSON> list = new ArrayList();
index.find(Filters.eq("isPublic", isPublic)).forEach((Consumer<? super Document>) (Document doc) -> {
if(loggedInUser != null && doc.getString("storePath").startsWith(loggedInUser) && !isPublic) {
// It's the user store
list.add(
new IndexJSON(doc.getString("storePath"), doc.getString("checksum"), doc.getString("lastUpdatedBy")));
} else if(isPublic)
list.add(
new IndexJSON(doc.getString("storePath"), doc.getString("checksum"), doc.getString("lastUpdatedBy")));
});
return list.toArray(new IndexJSON[list.size()]);
}
示例11: collectVectors
import com.mongodb.client.model.Filters; //导入依赖的package包/类
@Override
protected void collectVectors(Collection<String> terms, int limit) {
Set<String> toFetch = terms.stream()
.filter(t -> !this.vectorsCache.containsKey(t))
.collect(Collectors.toSet());
logger.debug("Cache has {} vectors, need to fetch more {}",
terms.size() - toFetch.size(), toFetch.size());
if (!toFetch.isEmpty()) {
logger.info("Collecting {} term vectors from {}", toFetch.size(), dbName);
FindIterable<Document> docs = getTermsColl().find(Filters.in(TERM_FIELD_NAME, toFetch));
if (docs != null) {
docs.batchSize(toFetch.size());
for (Document doc : docs) {
this.vectorsCache.put(doc.getString(TERM_FIELD_NAME), unmarshall(doc, limit));
}
}
}
}
示例12: update
import com.mongodb.client.model.Filters; //导入依赖的package包/类
/**
* @decription 更新数据
* @author yi.zhang
* @time 2017年6月2日 下午6:19:08
* @param table 文档名称(表名)
* @param obj
* @return
*/
public int update(String table, Object obj) {
try {
if(session==null){
init(servers, database, schema, username, password);
}
MongoCollection<Document> collection = session.getCollection(table);
if (collection == null) {
return 0;
}
JSONObject json = JSON.parseObject(JSON.toJSONString(obj));
Document value = Document.parse(JSON.toJSONString(obj));
collection.replaceOne(Filters.eq("_id", json.containsKey("_id")?json.get("_id"):json.get("id")), value);
return 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
示例13: delete
import com.mongodb.client.model.Filters; //导入依赖的package包/类
/**
* @decription 删除数据
* @author yi.zhang
* @time 2017年6月2日 下午6:19:25
* @param table 文档名称(表名)
* @param obj
* @return
*/
public int delete(String table, Object obj) {
try {
if(session==null){
init(servers, database, schema, username, password);
}
MongoCollection<Document> collection = session.getCollection(table);
if (collection == null) {
return 0;
}
JSONObject json = JSON.parseObject(JSON.toJSONString(obj));
collection.findOneAndDelete(Filters.eq("_id", json.containsKey("_id")?json.get("_id"):json.get("id")));
return 1;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
示例14: getChatById
import com.mongodb.client.model.Filters; //导入依赖的package包/类
public static ChatObj getChatById(String chatId, String chatGroupId) {
if (StringUtil.stringIsNull(chatId) || StringUtil.stringIsNull(chatGroupId)) {
return null;
}
Bson filter = Filters.eq(ChatObj.CHAT_ID, chatId);
List<ChatObj> list = MongodbManager.find(chatGroupId, filter, ChatObj.class, 0, 0);
if (list != null && list.size() != 0) {
return list.get(0);
} else {
return null;
}
}
示例15: getUserChatNum
import com.mongodb.client.model.Filters; //导入依赖的package包/类
public static long getUserChatNum(String toTypeId, String fromUserId, String chatCreateTime) {
if (StringUtil.stringIsNull(toTypeId) || StringUtil.stringIsNull(fromUserId)) {
return 0;
}
Date date = null;
if (!StringUtil.stringIsNull(chatCreateTime)) {
date = TimeUtils.stringToDateDay(chatCreateTime);
}
Bson filter = null;
if (!StringUtil.stringIsNull(chatCreateTime)) {
filter = Filters.lt(ChatObj.CHAT_CREATE_TIME, String.valueOf(date.getTime()));
}
long count = MongodbManager.count(getUserToUserCollectionName(toTypeId, fromUserId), filter);
return count;
}