Mongo shell command:
db.runCommand({compact: <collection name>})
How can I run same command using MongoTemplate in Spring Boot project?
I tried with:
#Autowired
private MongoTemplate mongoTemplate;
...
mongoTemplate.executeCommand(jsonCommand);
...
but it supports only commands in json.
According to docs you can call executeCommand using DBObject or String as a parameter.
So one option is simply get the JSON as String:
String jsonCommand = "{compact: " + collectionName + "}";
mongoTemplate.executeCommand(jsonCommand);
Or create the DBObject:
DBObject dbObject = new BasicDBObject("compact", collectionName );
mongoTemplate.executeCommand(dbObject);
Or even, according to this answer you can create the DBObject from a JSON:
BasicDBObject dbObject = com.mongodb.BasicDBObject.parse(jsonCommand)
mongoTemplate.executeCommand(dbObject);
Related
I need to print the MongoDB aggregation query used in Java code (for debugging an empty response). I don't see a way to print the GroupOperation object, org.springframework.data.mongodb.core.aggregation.GroupOperation
I see this method:
public Document toDocument(AggregationOperationContext context), but I don't understand how to pass a value for context.
I need a way to print this object.
Here are my code snippets:
Query in Java code:
GroupOperation groupOperation = new GroupOperation(
Fields.fields("dbHost"))
.first("dbUser").as("dbUser")
.first("dbPassword").as("dbPassword");
System.out.println("groupOperation = " + groupOperation);
List<AggregationOperation> aggregationOperations = Lists.newArrayList(groupOperation);
Aggregation agg = Aggregation.newAggregation(aggregationOperations)
.withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
AggregationResults<Document> aggInfo = mongoTemplate.aggregate(agg, "schedulerInfo", Document.class);
List<Document> docs = aggInfo.getMappedResults();
System.out.println("docs = " + docs);
Output:
groupOperation = org.springframework.data.mongodb.core.aggregation.GroupOperation#1188e820
docs = []
Corresponding query in Mongo shell:
db.schedulerInfo.aggregate([{"$group": {"_id": "$dbHost", "dbUser": { "$first": "$dbUser" },"dbPassword": { "$first": "$dbPassword" }}}])
I have a collection with several fields and would like to update both the field name through Java program. For example
{_id : ObjectId(xxxxxxxxxxxx), field1: "value1", field2 : "value2"}
Now I have a requirement to rename the field1 to say field11. How do I do it using Spring Data.
Basically this ops using Java
https://docs.mongodb.com/manual/reference/operator/update/rename/
#Autowired
MongoTemplate mongoTemplate;
void renameFunction() {
BasicDBObject searchQuery = new BasicDBObject();
BasicDBObject updateQuery = new BasicDBObject();
updateQuery.append("$rename",new BasicDBObject().append("field1", "field11").append("field2", "field22"));
mongoTemplate.getCollection("Collection_Name").updateMany(searchQuery,updateQuery);
}
I need to replace a whole existing document of mongodb from java instead of setting every field.Is there any way? I am using mongo morphia.
Right now i am setting fields one by one ,following is code :
DBObject searchObject =new BasicDBObject();
searchObject.put("procId", procId);
final UpdateOperations<Timesheet> updateOperations = ds.createUpdateOperations(Timesheet.class)
.set("wheelInTime", timesheet.getWheelInTime())
.set("wheelOutTime", timesheet.getWheelOutTime())
.set("tableOnTime", timesheet.getTableOnTime())
.set("tableOffTime", timesheet.getTableOffTime())
final UpdateResults results = ds.updateFirst(findQuery,updateOperations);
You can 'overwrite' any entry in a MongoDB collection but simply creating a new DbObject with the same _id field and saving it to the database. So just set the fields in your object as you would any Java object and use myCollection.save(obj)
Just save the object and it will overwrite the document with the same #id. This can be done with one line of code:
dao.save(timesheet);
More complete example code of the usage of the Morphia DAO:
class Dao extends BasicDAO<TimeSheet, String> {
Dao(Datastore ds) {
super(TimeSheet.class, ds);
}
}
Datastore ds = morphia.createDatastore(mongoClient, DB_NAME);
Dao dao = new Dao(ds);
dao.save(timesheet);
I am trying to get the Data from Mongodb whose Model/Domain is unknown.
Can i get that using Mongo Template.
e.g.
mongoTemplate.find(query,<Dynamic Class?>)
You can use DBObject. If you take a look at its implementations (BasicDBObject...) it's an HashMap (key/values) containing all fields:
#Autowired
private MongoTemplate mongoTemplate;
DBObject query = new BasicDBObject("field", "value");
DBCursor dbCursor = mongoTemplate.getCollection("collectionName").find(query);
Iterator<DBObject> iterator = dbCursor.iterator();
while(iterator.hasNext()){
Object value = iterator.next().get("otherfield");
}
I have the following code:
#RequestMapping(value = "/envinfo", method = RequestMethod.GET)
#ResponseBody
public Map getEnvInfo()
{
BasicQuery basicQuery = new BasicQuery("{_id:'51a29f6413dc992c24e0283e'}", "{'envinfo':1, '_id': false }");
Map envinfo= mongoTemplate.findOne(basicQuery, Map.class, "jvmInfo");
return envinfo;
}
As you can notice, the code:
Retrieves JSON from MongoDB
Converts it to a Map object
The Map object is then converted to JSON by Spring MongoData before it is returned to the browser.
Is it possible to directly return the raw json from MongoDb without going through the intermediate conversion steps?
There's two way's you can do this right now:
1. Using the CollectionCallback on MongoTemplate
You can use a CollectionCallback to deal with the returned DBObject directly and simply toString() it:
template.execute("jvmInfo", new CollectionCallback<String>() {
String doInCollection(DBCollection collection) {
DBCursor cursor = collection.find(query)
return cursor.next().toString()
}
}
Yo'll still get the exception translation into Spring's DataAccessExceptions. Note, that this is slightly brittle as we expect only a single result to be returned for the query but that's probably something you have to take care of when trying to produce a String anyway.
2. Register a Converter from DBObject to String
You can implement a Spring Converter to do the toString() for you.
class DBObjectToStringConverter implements Converter<DBObject, String> {
public String convert(DBObject source) {
return source == null ? null : source.toString();
}
}
You can then either use the XML configuration or override customConversions() to return a new CustomConversions(Arrays.asList(new DBObjectToStringConverter())) to get it registered with your MongoConverter. You can then simply do the following:
String result = mongoTemplate.findOne(basicQuery, String.class, "jvmInfo");
I will add the just showed converter to Spring Data MongoDB and register it by default for the upcoming 1.3 GA release and port the fix back to 1.2.x as part of the fix for DATAMONGO-743.
As Oliver points out, you can use Spring Data for that, but an alternative which you may or may not prefer would be to use MongoDB's more low-level Java Driver. Take a look at the MongoDB Java Driver 3.x or MongoDB Java Driver 2.x documentation for instructions on using that driver.
Basically, what you need to do is this:
MongoDB Java Driver 3.x
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e");
try (MongoCursor<Document> cursor = collection.find(query).iterator()) {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}
MongoDB Java Driver 2.x
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e");
try (DBCursor cursor = coll.find(query)) {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}
That will print out all the documents in the collection that have a field _id with a value 51a29f6413dc992c24e0283e.
For me the following worked perfectly:
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.bson.Document;
List<Document> documents = mongoTemplate.find(query, Document.class, "collection_name");