下面列出了com.mongodb.DBObject#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onApplicationEvent(MongoMappingEvent<?> event) {
if (!(event instanceof BeforeSaveEvent)) {
return;
}
if (!IdentifiableEntity.class.isAssignableFrom(event.getSource().getClass())) {
return;
}
IdentifiableEntity source = (IdentifiableEntity) event.getSource();
if (source.getId() != null) {
return;
}
DBObject dbObject = event.getDBObject();
String id = sequenceService.getNextIt(event.getSource().getClass());
source.setId(id);
dbObject.put("_id", id);
}
/**
* set the state of balancer.
*
* @param dbConn
* @param state
* @return Error description, or null if no errors
*/
private static String setBalancerState(DB dbConn, boolean state) {
DBObject balancer = new BasicDBObject(ID, "balancer");
DBObject updateObj = new BasicDBObject();
String stopped = state ? "false" : "true";
updateObj.put("$set", new BasicDBObject("stopped", stopped));
WriteResult wresult = dbConn.getSisterDB("config").getCollection("settings").update(balancer, updateObj, true, false);
if (wresult != null) {
CommandResult result = wresult.getLastError();
if (!result.ok()) {
LOG.error("Error setting balancer state to {}: {}", state, result.getErrorMessage());
return result.getErrorMessage();
}
}
return null;
}
@Test
public void testQueryAllFromMongo() {
int count = 10;
for ( int i=0; i<count; i++ ) {
DBObject dbObject = new BasicDBObject();
dbObject.put("_id", i);
dbObject.put("name", "value"+i);
MongoDBUtil.saveToMongo(dbObject, dbObject, testDB, null, "mongoutil", true);
}
DBObject fields = new BasicDBObject();
fields.put("name", "1");
List<DBObject> result = MongoDBUtil.queryAllFromMongo(new BasicDBObject(), testDB, null, "mongoutil", fields);
assertEquals(10, result.size());
}
public BuguQuery<T> text(String value, boolean caseSensitive){
DBObject dbo = new BasicDBObject();
dbo.put(Operator.SEARCH, value);
dbo.put(Operator.CASE_SENSITIVE, caseSensitive);
condition.put(Operator.TEXT, dbo);
return this;
}
public Object toDBObject() {
DBObject dbObject = new BasicDBObject();
dbObject.put("text", text);
dbObject.put("reviewId", reviewId);
dbObject.put("business", business);
return dbObject;
}
private DBObject humanToObject(HumanAccountData account) {
DBObject object = new BasicDBObject();
PasswordDigest digest = account.getPasswordDigest();
if (digest != null) {
DBObject digestObj = new BasicDBObject();
digestObj.put(PASSWORD_SALT_FIELD, digest.getSalt());
digestObj.put(PASSWORD_DIGEST_FIELD, digest.getDigest());
object.put(HUMAN_PASSWORD_FIELD, digestObj);
}
if (account.getEmail() != null) {
object.put(EMAIL_FIELD, account.getEmail());
}
if (account.getRecoveryToken() != null) {
object.put(TOKEN_FIELD, account.getRecoveryToken().getToken());
object.put(TOKEN_DATE_FIELD, account.getRecoveryToken().getExpirationDate());
}
if (account.getLocale() != null) {
object.put(ACCOUNT_LOCALE, account.getLocale());
}
if (account.getAvatarFileName() != null) {
object.put(ACCOUNT_AVATAR_FILE, account.getAvatarFileId());
}
if (account.getName() != null) {
object.put(NAME_FIELD, account.getName());
}
return object;
}
@Test
public void parseValue() {
final EventParser eventParser = new EventParser();
assertThat(eventParser.parseValue(definition(MongoDataType.STRING), "foo")).isEqualTo("foo");
assertThat(eventParser.parseValue(definition(MongoDataType.INT32), "32")).isEqualTo(32);
assertThat(eventParser.parseValue(definition(MongoDataType.INT64), "64")).isEqualTo(64L);
assertThat(eventParser.parseValue(definition(MongoDataType.DOUBLE), "1.0")).isEqualTo(1.0);
assertThat(eventParser.parseValue(definition(MongoDataType.BOOLEAN), "true")).isEqualTo(true);
final DateTime now = DateTime.now().toDateTime(DateTimeZone.UTC);
assertThat(eventParser.parseValue(definition(MongoDataType.DATE), Long.toString(now.getMillis()))).isEqualTo(
now.toDate());
assertThat((eventParser.parseValue(definition(MongoDataType.DATE), ISODateTimeFormat.dateTime().print(now))))
.isEqualTo(
now.toDate());
assertThat(eventParser.parseValue(definition(MongoDataType.NULL), "full")).isNull();
assertThat(eventParser.parseValue(definition(MongoDataType.OBJECTID), "507c7f79bcf86cd7994f6c0e")).isEqualTo(
new ObjectId("507c7f79bcf86cd7994f6c0e"));
BasicDBList dbList = new BasicDBList();
dbList.add(1);
dbList.add(2);
dbList.add(3);
DBObject dbObject = new BasicDBObject();
dbObject.put("abc", 123);
dbObject.put("myArray", dbList);
assertThat(eventParser.parseValue(definition(MongoDataType.OBJECT), "{ \"abc\": 123, \"myArray\": [1, 2, 3] }"))
.isEqualTo(
dbObject);
assertThat(eventParser.parseValue(definition(MongoDataType.BINARY), "U3RyYXRpbw==")).isEqualTo(
"Stratio".getBytes(Charsets.UTF_8));
}
/**
* Match: lessThan minValue or greaterThan maxValue.
* @param key
* @param minValue
* @param maxValue
* @return
*/
public BuguQuery<T> notBetween(String key, Object minValue, Object maxValue){
DBObject dbo = new BasicDBObject();
dbo.put(Operator.GTE, minValue);
dbo.put(Operator.LTE, maxValue);
append(key, Operator.NOT, dbo);
return this;
}
public static void testMapDBObject(int max, DB db) {
String collName = "testmapobject";
DBCollection coll = db.getCollection(collName);
//Setup a sharded collection
BasicDBObject command = new BasicDBObject();
command.put("shardcollection", collName);
DBObject key = new BasicDBObject();
key.put("_id", 1);
command.put("key", key);
command.put("unique", true);
db.command(command);
long startM = System.currentTimeMillis();
BasicDBObject objKey = new BasicDBObject();
UserId userId = new UserId("username");
objKey.put("_id", userId.getInternal());
MapDBObject obj = new MapDBObject();
for ( int i=0; i<max; i++ ) {
obj.put("_id", userId.getInternal());
obj.put("test-"+(i)%10, "value-"+i);
coll.update(objKey, obj, true, false);
}
long endM = System.currentTimeMillis();
System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(114892)");
CommandResult result = db.getStats();
System.out.println(result);
}
@Override
public void setQuery(DBObject query, BasicDBList orList) {
if (null == orList) {
query.put(this.name, new BasicDBObject("$lt", value.getValue()));
} else {
orList.add(new BasicDBObject(this.name, new BasicDBObject("$lt", value.getValue())));
}
}
private void updateSamplingData(DBObject data) {
if (data.containsField("information")) {
DBObject info = (DBObject) data.get("information");
if (info.containsField("refid") && info.containsField("x") && info.containsField("y")) {
DBObject refpoint = mCollRef.findOne(info.get("refid"));
if (refpoint != null && refpoint.containsField("x") && refpoint.containsField("y") && refpoint.containsField("floor")
&& refpoint.containsField("floor_num")) {
AffineTransform at = new AffineTransform();
at.translate(((Number) refpoint.get("x")).doubleValue(), ((Number) refpoint.get("y")).doubleValue());
at.rotate(Math.toRadians(((Number) refpoint.get("rotate")).doubleValue()));
Point2D.Double src = new Point2D.Double(((Number) info.get("x")).doubleValue(), ((Number) info.get("y")).doubleValue());
Point2D.Double dst = new Point2D.Double();
at.transform(src, dst);
info.put("absx", dst.getX());
info.put("absy", dst.getY());
info.put("floor", refpoint.get("floor"));
info.put("floor_num", refpoint.get("floor_num"));
System.out.println(JSON.serialize(info));
} else {
info.put("absx", ((Number) info.get("x")).doubleValue());
info.put("absy", ((Number) info.get("y")).doubleValue());
}
}
}
}
public DBObject toDBObject() {
DBObject dbo = new BasicDBObject();
dbo.put(SPHERICAL, spherical);
if (limit != 0) {
dbo.put(LIMIT, limit);
}
if (num != 0) {
dbo.put(NUM, num);
}
if (maxDistance != 0) {
dbo.put(MAX_DISTANCE, maxDistance);
}
if (minDistance != 0) {
dbo.put(MIN_DISTANCE, minDistance);
}
if (query != null) {
dbo.put(QUERY, BasicDBObject.parse(query));
}
if (near != null) {
dbo.put(NEAR, MapperUtil.toDBObject(near, true));
}
if (distanceField != null) {
dbo.put(DISTANCE_FIELD, distanceField);
}
if (includeLocs != null) {
dbo.put(INCLUDE_LOCS, includeLocs);
}
return dbo;
}
@Override
public void setQuery(DBObject query, BasicDBList orList) {
if (null == orList) {
query.put(this.name, new BasicDBObject("$gte", value.getValue()));
} else {
orList.add(new BasicDBObject(this.name, new BasicDBObject("$gte", value.getValue())));
}
}
@Override
public BasicUser queryBasicUser(String userName) {
DBObject query = createDBObject();
query.put(LOGIN_USERNAME, userName);
DBObject userObj = MongoDBUtil.queryFromMongo(query, databaseName, namespace, USER_COLL_NAME, basicUserFields);
BasicUser user = null;
if ( userObj != null ) {
user = constructBasicUserObject(userObj);
}
return user;
}
@Test
public void testSparky() throws Exception {
Chart chart = ChartUtil.loadChart("charts/linechart.json");
JsonNode metricSpecification = ChartUtil.loadJsonFile("data/commitsovertime.json");
JsonNode vis = metricSpecification.get("vis").get(0);
MetricVisualisation mv = new MetricVisualisation(chart, metricSpecification, vis);
DB db = mongo.getDB("Xtext");
DBCollection collection = db.getCollection(metricSpecification.path("metricid").textValue());
Random random = new Random();
int commits = 0;
Date[] range = Date.range(new Date("20140101"), new Date("20140130"));
for (Date d : range) {
CommitsOverTime cot = new CommitsOverTime();
RepositoryData rd = new RepositoryData();
rd.setUrl("foo");
rd.setNumberOfCommits(commits);
commits = commits + (random.nextInt(10));
cot.getRepositories().add(rd);
DBObject dbObject = cot.getDbObject();
dbObject.put("__date", d.toString());
dbObject.put("__datetime", d.toJavaDate());
collection.save(dbObject);
}
byte[] sparky = mv.getSparky(db, null);
for (byte b : sparky) System.out.println(b);
System.out.println(sparky);
}
private DBObject getDBObjectForParticipant(ParticipantId id) {
DBObject query = new BasicDBObject();
query.put("_id", id.getAddress());
return query;
}
private DBObject populateDocument() throws ParseException {
final DBObject document = new BasicDBObject();
document.put("santanderID", "documentID");
document.put("date", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse("2014-12-16T16:32:33"));
return document;
}
private static String preSplitBinCollections(String dbName, MongoTemplate mongoTemplate) {
DB dbConn = mongoTemplate.getDb().getSisterDB("admin");
List<String> shards = getShards(dbConn);
if (shards != null && shards.size() > 0) {
int numShards = shards.size();
List<String> collections = Arrays.asList("recordHash", "deltas");
for (String collectionName: collections) {
LOG.info("Shard count = {}. Setting up sharding config for {}!", numShards, collectionName);
String collection = dbName + "." + collectionName;
DBObject shardColl = new BasicDBObject();
shardColl.put("shardCollection", collection);
shardColl.put("key", new BasicDBObject(ID, 1));
CommandResult result = dbConn.command(shardColl);
if (!result.ok()) {
LOG.error("Error enabling shard'ing on recordHash: {}", result.getErrorMessage());
return result.getErrorMessage();
}
int charOffset = 256 / numShards;
List<byte[]> shardPoints = new ArrayList<byte[]>();
shardPoints.add(null);
for (int shard = 1; shard < numShards; shard++) {
String splitString = Integer.toHexString(charOffset * shard);
if (splitString.length() < 2) {
splitString = "0" + splitString;
}
splitString = splitString + STR_0X38;
byte[] splitPoint = RecordHash.hex2Binary(splitString);
shardPoints.add(splitPoint);
LOG.info("Adding recordHash splitPoint [" + RecordHash.binary2Hex(splitPoint) + "]");
DBObject splitCmd = new BasicDBObject();
splitCmd.put("split", collection);
splitCmd.put("middle", new BasicDBObject(ID, splitPoint));
result = dbConn.command(splitCmd);
if (!result.ok()) {
LOG.error("Error splitting chunk in recordHash: {}", result.getErrorMessage());
return result.getErrorMessage();
}
}
for (int index = 0; index < numShards; index++) {
DBObject moveCommand = new BasicDBObject();
moveCommand.put("moveChunk", collection);
moveCommand.put("find", new BasicDBObject(ID, index == 0 ? "$minkey" : shardPoints.get(index)));
moveCommand.put("to", shards.get(index));
result = dbConn.command(moveCommand);
if (!result.ok()) {
if (!result.getErrorMessage().equals("that chunk is already on that shard")) {
LOG.error("Error moving chunk in recordHash: {}", result.getErrorMessage());
return result.getErrorMessage();
}
}
}
}
} else {
LOG.info("No shards or shard count < 0. Not setting sharding config for recordHash!");
}
return null;
}
public List<Chemical> getChemicalsThatHaveField(String field) {
DBObject val = new BasicDBObject();
val.put("$exists", "true");
return constructAllChemicalsFromActData(field, val);
}
@Test
public void testRascalDatatable() throws Exception {
// Create test data
DB db = mongo.getDB("rascalloc");
DBCollection collection = db.getCollection("locperlanguage");
Calendar cal = Calendar.getInstance();
for (int i = 0; i < 10; i++) {
ListMeasurement list = new ListMeasurement();
for (String lang : new String[]{"HTML", "Java", "PHP"}) {
StringMeasurement l = new StringMeasurement();
l.setValue(lang);
IntegerMeasurement loc = new IntegerMeasurement();
loc.setValue(3);
TupleMeasurement tuple = new TupleMeasurement();
tuple.getValue().add(l);
tuple.getValue().add(loc);
list.getValue().add(tuple);
}
DBObject obj = list.getDbObject();
obj.put("__date", new org.eclipse.scava.platform.Date(cal.getTime()).toString());
obj.put("__datetime", cal.getTime());
collection.save(obj);
cal.add(Calendar.DATE, 1);
}
JsonNode node = ChartUtil.loadJsonFile("data/rascalloc.json");
ArrayNode vis = (ArrayNode) node.get("vis");
JsonNode datatable = vis.get(0).get("datatable");
Chart chart = ChartUtil.loadChart("charts/linechart.json");
ArrayNode table = chart.createDatatable(datatable, collection, null);
System.out.println(table);
// Tidy up
mongo.dropDatabase("rascalloc");
}