@Override public List<SystemMessage> all(int page) { List<SystemMessage> messages = Lists.newArrayList(); DBObject sort = new BasicDBObject(); sort.put("timestamp", -1); List<DBObject> results = query(SystemMessageImpl.class, new BasicDBObject(), sort, PER_PAGE, PER_PAGE * page); for (DBObject o : results) { messages.add(new SystemMessageImpl(new ObjectId(o.get("_id").toString()), o.toMap())); } return messages; }
/** * Generate new Id, based on machine/process, current seconds and inrementing counter. * Should be treated as opaque holder though. * @return the id */ public static Id generate() { return from(ObjectId.get()); }
public static CollectorActions create(String sidecar_id, DateTime created, List<CollectorAction> action) { return create( new org.bson.types.ObjectId().toHexString(), sidecar_id, created, action); } }
@Test public void testDeleteDoesNotDeleteAnythingWhenGivenAnIncorrectId() { // given final String ns = "someCollectionName"; getDb().getCollection(ns).remove(new BasicDBObject()); final Rectangle rect = new Rectangle(10, 10); ObjectId id = new ObjectId(); rect.setId(id); getAds().save(ns, rect); assertEquals(1, getAds().find(ns, Rectangle.class).count()); // when giving an ID that is not the entity ID. Note that at the time of writing this will also log a validation warning getAds().delete(getAds().find(ns, Rectangle.class).filter("_id", 1)); // then assertEquals(1, getDb().getCollection(ns).count()); }
public <T> boolean exists(Class<T> entity, String id) throws OperatorException { DBObject _obj = new BasicDBObject(); _obj.put(MongoDB.OPT.ID, new ObjectId(id)); return __clientHolder.getDB().getCollection(MongoEntitySupport.getEntityName(entity)).findOne(_obj) != null; }
protected <T extends Persisted> void removeEmbedded(T model, String key, String searchId) { BasicDBObject aryQry = new BasicDBObject("id", searchId); BasicDBObject qry = new BasicDBObject("_id", new ObjectId(model.getId())); BasicDBObject update = new BasicDBObject("$pull", new BasicDBObject(key, aryQry)); // http://docs.mongodb.org/manual/reference/operator/pull/ collection(model).update(qry, update); }
@Override public <T extends Persisted> String save(T model) throws ValidationException { Map<String, List<ValidationResult>> errors = validate(model, model.getFields()); if (!errors.isEmpty()) { throw new ValidationException(errors); } BasicDBObject doc = new BasicDBObject(model.getFields()); doc.put("_id", new ObjectId(model.getId())); // ID was created in constructor or taken from original doc already. // Do field transformations fieldTransformations(doc); /* * We are running an upsert. This means that the existing * document will be updated if the ID already exists and * a new document will be created if it doesn't. */ BasicDBObject q = new BasicDBObject("_id", new ObjectId(model.getId())); collection(model).update(q, doc, true, false); return model.getId(); }
@Override public ConversationState getConversationState(String conversationId) { Document conversationMemoryDocument = conversationCollection.find( new Document(OBJECT_ID, new ObjectId(conversationId))). projection(new Document(CONVERSATION_STATE_FIELD, 1).append(OBJECT_ID, 0)). first(); if (conversationMemoryDocument != null && conversationMemoryDocument.containsKey(CONVERSATION_STATE_FIELD)) { return ConversationState.valueOf(conversationMemoryDocument.get(CONVERSATION_STATE_FIELD).toString()); } return null; }
@Test(expected = IllegalArgumentException.class) public void shouldNotRenameNestedFieldsToExistingNamesForSetNestedFieldUpdateEventWithArrayOfEmbeddedDocuments() throws InterruptedException { // given CollectionId collectionId = new CollectionId("rs0", "dbA", "c1"); ObjectId objId = new ObjectId(); Document obj = new Document() .append("$set", new Document() .append("name", "Sally") .append("addresses.0.number", 34L) .append("addresses.0.street", "Claude Debussylaan") .append("addresses.0.city", "Amsterdam")); Filters filters = build.renameFields("*.c1.addresses.street:city").createFilters(); List<SourceRecord> produced = new ArrayList<>(); RecordMakers recordMakers = new RecordMakers(filters, source, topicSelector, produced::add, true); // when recordMakers.forCollection(collectionId).recordEvent(createUpdateEvent(obj, objId), 1002); }
@Override public void removeOutputFromAllStreams(Output output) { ObjectId outputId = new ObjectId(output.getId()); DBObject match = new BasicDBObject(StreamImpl.FIELD_OUTPUTS, outputId); DBObject modify = new BasicDBObject("$pull", new BasicDBObject(StreamImpl.FIELD_OUTPUTS, outputId)); // Collect streams that will change before updating them because we don't get the list of changed streams // from the upsert call. final ImmutableSet<String> updatedStreams; try (final DBCursor cursor = collection(StreamImpl.class).find(match)) { updatedStreams = StreamSupport.stream(cursor.spliterator(), false) .map(stream -> stream.get("_id")) .filter(Objects::nonNull) .map(id -> ((ObjectId) id).toHexString()) .collect(ImmutableSet.toImmutableSet()); } collection(StreamImpl.class).update( match, modify, false, true ); clusterEventBus.post(StreamsChangedEvent.create(updatedStreams)); }
@Override public Map<String, Long> streamRuleCountByStream() { final ImmutableMap.Builder<String, Long> streamRules = ImmutableMap.builder(); try(DBCursor streamIds = collection(StreamImpl.class).find(new BasicDBObject(), new BasicDBObject("_id", 1))) { for (DBObject keys : streamIds) { final ObjectId streamId = (ObjectId) keys.get("_id"); streamRules.put(streamId.toHexString(), streamRuleCount(streamId)); } } return streamRules.build(); }
@Test public void shouldExcludeFieldsForDeleteTombstoneEvent() throws InterruptedException { // given CollectionId collectionId = new CollectionId("rs0", "dbA", "c1"); ObjectId objId = new ObjectId(); Document obj = new Document("_id", objId); Filters filters = build.excludeFields("*.c1.name,*.c1.active").createFilters(); List<SourceRecord> produced = new ArrayList<>(); RecordMakers recordMakers = new RecordMakers(filters, source, topicSelector, produced::add, true); // when recordMakers.forCollection(collectionId).recordEvent(createEvent(obj, "d"), 1002); // then SourceRecord record = produced.get(1); assertThat(record.value()).isNull(); }
MongoClient mongo = new MongoClient("localhost", 27017); DB db = mongo.getDB("test"); DBCollection collection = db.getCollection("collection"); DBObject obj = collection.findOne(new BasicDBObject("name", new BasicDBObject( "$exists", true)),new BasicDBObject("_id",1)); ObjectId id = (ObjectId) obj.get("_id"); System.out.println(id.toHexString());
MongoDatabase db1 = mongo.getDatabase("dbit"); MongoCollection<Document> coll = db1.getCollection("arbitrary"); coll.drop(); Document doc = Document.parse("{\"a\": 1, \"b\": 2}"); InsertOneOptions insertOptions = new InsertOneOptions().bypassDocumentValidation(true); coll.insertOne(doc, insertOptions); doc = coll.find().first(); Testing.debug("Document: " + doc); id.set(doc.getObjectId("_id").toString()); Testing.debug("Document ID: " + id.get()); }); Document doc = coll.find().first(); Testing.debug("Document: " + doc); Document filter = Document.parse("{\"a\": 1}"); Document operation = Document.parse("{ \"$set\": { \"b\": 10 } }"); coll.updateOne(filter, operation); doc = coll.find().first(); Testing.debug("Document: " + doc); });
private Document parseUpdateKey(String updateKey, Map doc) { Document retVal; if (updateKey.equals("_id") && ObjectId.isValid(((String) doc.get(updateKey)))) { retVal = new Document("_id", new ObjectId((String) doc.get(updateKey))); } else if (updateKey.contains(",")) { String[] parts = updateKey.split(",[\\s]*"); retVal = new Document(); for (String part : parts) { retVal.append(part, doc.get(part)); } } else { retVal = new Document(updateKey, doc.get(updateKey)); } return retVal; }
peopleCollection.deleteMany(new Document()); peopleCollection.insertMany(Arrays.asList( new Document() .append("_id", new ObjectId("582ecee28feed271b9f54e58")) .append("name", "Paul") .append("position", "developer") .append("age", 25), new Document() .append("_id", new ObjectId("582ecee28feed271b9f54e59")) .append("name", "Melissa") .append("position", "developer") .append("age", 26), new Document() .append("_id", new ObjectId("582ecee28feed271b9f54e60")) .append("name", "Roger") .append("position", "manager") .append("age", 27), new Document() .append("_id", new ObjectId("582ecee28feed271b9f54f58")) .append("name", "Shirley") .append("comment", "director")
final ImmutableSet.Builder<String> modifiedAlertConditions = ImmutableSet.builder(); for (Document document : collection.find().sort(ascending(FIELD_CREATED_AT))) { final String streamId = document.getObjectId(FIELD_ID).toHexString(); if (!document.containsKey(FIELD_ALERT_CONDITIONS)) { continue; final List<Document> alertConditions = (List<Document>) document.get(FIELD_ALERT_CONDITIONS); final UpdateResult result = collection.updateOne(eq(FIELD_ALERT_CONDITIONS_ID, alertConditionId), set(ALERT_CONDITIONS_PARAMETERS_PREFIX + field, intValue));