getting a pojo from a mongo doc using morphia - mongodb

Please can someone explain me this code using to create a pojo from a mongo doc? Is it necessary to create a class which contain database fields+getters and setters?
Morphia morphia=....;
MongoClient mongoClient = ............;
DB db = mongoClient.getDB( "contact" );
String contactId=.....;
//load the object from the collection
BasicDBObject idObj=new BasicDBObject ("_id", new ObjectId(contactId));
BasicDBObject obj=(BasicDBObject db.getCollection("personnal").findOne(idObj);
Contact contacy=morphia.fromDBObject(Contact.class,obj);
What value must be afect to contactId?

Why aren't you using Morphia's API if you have it available?
datastore.get(Contact.class, new ObjectId(contactId));

Related

How do you check if a collection is capped?

Before, using spring data mongo you could do something like mongoClient.getDB(db_name).getCollection(collection_name).isCapped(). But now the getDB is deprecated, you could still use it but there must be some other way to do it.
I tried doing mongoClient.getDatabase(db_name).getCollection(collection_name).some_function() but there is no similar function like isCapped() now.
You can achieve to find if a collection is capped by doing the following.
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient(), getDatabaseName());
Document obj = new Document();
obj.append("collStats", "yourCollection");
Document result = mongoTemplate.executeCommand(obj);
result.getBoolean("capped")

how to get all the documents in collection from mongoDB using spring

I was trying to get all the documents from a collection in mongoDB , I am using spring.
MongoTemplate mongoOperation = SpringMongoConfig1.mongoTemplate()
Here in monngoOperation I did not find any method which returns all the docs from a collection .
can anyone help in this ?
If you want to find all the documents of JavaDocumentName(any collection name in java)
List<JavaDocumentName> listRes = mongoOperation.findAll(JavaDocumentName.class);
You can do like this:
//If you don't need connection's configures. i.e. your mongo is in you localhost at 127.0.0.1:27017
MongoClient cliente = new MongoClient(); //to connect into a mongo DB
MongoDatabase mongoDb = client.getDatabase("DBname"); //get database, where DBname is the name of your database
MongoCollection<Document> robosCollection = mongoDb.getCollection("collectionName"); //get the name of the collection that you want
MongoCursor<Document> cursor = robosCollection.find().cursor();//Mongo Cursor interface implementing the iterator protocol
cursor.forEachRemaining(System.out::println); //print all documents in Collection using method reference

How to fetch mongo db data and pass in jmeter request

I have one post call that response is like this.
{
"status":0,
"message":"Prescription Created",
"jsonResponse":{},
"cid":"C5975K",
"pid":"Rx5975K-175A",
"prescriptionSource":"GO_RX_CTO",
"imageStatus":[]
}
By taking this pid , I have to do the query for the one more record. For example:
db.order.find({"pid":"Rx5975K-175A"})
and the result of this query should pass in one more jmeter request.
I have used MongoDB Script (DEPRECATED) .. But this wont work as its deprecated ..
Tried with JSR223 Sampler, but its not working in new jmeter 3.2
import com.mongodb.*
import com.mongodb.BasicDBObject
MongoCredential coreCredential = MongoCredential.createCredential("${mongodb_user}", "${mongodb_database}", "${mongodb_password}".toCharArray());
MongoClient coreMongoClient = new MongoClient(new ServerAddress("${mongodb_server}", 13017), Arrays.asList(coreCredential));
DB coreDB = coreMongoClient.getDB("${mongodb_database}");
DBCollection coll = coreDB.getCollection("order");
coll.find();
You have to find your result based on "pid" and you are nowhere passing it. After finding you collection you need to create a query and searching using that query.
import com.mongodb.*
import com.mongodb.BasicDBObject
MongoCredential coreCredential = MongoCredential.createCredential("${mongodb_user}", "${mongodb_database}", "${mongodb_password}".toCharArray());
MongoClient coreMongoClient = new MongoClient(new ServerAddress("${mongodb_server}", 13017), Arrays.asList(coreCredential));
DB coreDB = coreMongoClient.getDB("${mongodb_database}");
DBCollection coll = coreDB.getCollection("order");
BasicDBObject query = new BasicDBObject();
query.put("pid", "Rx5975K-175A");
DBObject getData= coll.findOne(query);
and this will give you the desire result

Insert DBObject into MongoDB using Spring Data

I tried to insert the following DBObject into MongoDB using Spring Data:
BasicDBObject document = new BasicDBObject();
document.put("country", "us");
document.put("city", "NY");
mongoTemplate.insert(document);
where mongoTemplate is my Spring template (org.springframework.data.mongodb.core.MongoTemplate).
When executing, I get:
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: No Persitent Entity information found for the class com.mongodb.BasicDBObject
at org.springframework.data.mongodb.core.MongoTemplate.determineCollectionName(MongoTemplate.java:1747)
at org.springframework.data.mongodb.core.MongoTemplate.determineEntityCollectionName(MongoTemplate.java:1732)
at org.springframework.data.mongodb.core.MongoTemplate.insert(MongoTemplate.java:658)
My JSON would be dynamic at the end. So any idea how to provide these entity information dynamically ?
Or is there another way to insert raw JSON into Mongodb through Spring Data ?
You are confusing spring-data with normal mongo persistence using the java driver.
If you want to persist data to mongoDB directly using the java driver then you would use the BasicDBObject like you have shown except that you would not use the mongoTemaplate class to persist but rather the MongoClient class. So it would look like this:
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "mydb" );
BasicDBObject o = new BasicDBObject();
o.set......
coll.insert(o);
But if you are trying to persist a document using spring-data, then you need to create a java class to represent your document (eg: Person) and annotate this class with #Document(collection="person") and then use the mongoTemplate (which is a spring-data specific class to persist this entity. This is very similar to using JPA/hibernate.
So it would look something like this
#Document(collection="person")
public class Person {
private String fisrtName;
....
Relevant getters and setters
}
And then the persistence
Person p = new Person();
p.setFirstName("foo");
p.setLastName("bar");
....
mongoTemplate.save(p);
Another way to do this is to directly access the DBCollection object via the MongoTemplate:
DBObject company = new BasicDBObject();
...
DBCollection collection = mongoTemplate.getCollection("company");
collection.insert(company);
Another way to do it
Import statements
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import org.springframework.data.mongodb.core.MongoTemplate;
Member Variables
#Autowired MongoTemplate mongoTemplate;
MongoCollection<Document> collection;
#PostConstruct
public void init(){
collection = mongoTemplate.getCollection("company");
}
And then, the method
public void insertRawData(){
Document company = new Document(new HashMap()); // If you have to insert a hashMap
// otherwise you can add one-by-one using company.put("foo","bar")
collection.insertOne(company);
}

Indexing MongoDB collection in Java

I am creating a collection in MongoDB in the following way and I want to create a 2dsphere index on location field of this collection from Java code. But I am not able to do so.
collection.ensureIndex() method expects a DBObject as a parameter but I cannot pass location to it.
How do I create collection.ensureIndex({"location" : "2dsphere"}) in Java code?
MongoDB allows me to do so in command prompt. But, I want to index it through code written in Java.
BasicDBObject doc = new BasicDBObject("attr1", nextLine[0])
.append("attr2", nextLine[1])
.append("edge-metro-code", nextLine[6])
.append("location", new BasicDBObject("type", "Point")
.append("coordinates",latLong))
.append("attr3", nextLine[9])
.append("attr4", nextLine[10])
ensureIndex() has been deprecated now. You should use createIndex() instead:
MongoClient mongoClient = new MongoClient();
DBCollection test = mongoClient.getDB("testdb").getCollection("test");
test.createIndex(new BasicDBObject("location","2dsphere"));
You should construct a new DBObject that represents your index. See the code bellow:
DBObject index2d = BasicDBObjectBuilder.start("location", "2dsphere").get();
DBCollection collection = new Mongo().getDB("yourdb").getCollection("yourcollection");
collection.ensureIndex(index2d);