MongoDB Exception caching while updating data - mongodb

Hello every one I'm new to mongodb. While i updating the table i have to get the return values in result. But it return undefined ,But in the case of find and insert the value in table it works properly.
bands.update({name:'Hollywood Rose'}, {$set:{year:2000}}, function(err, result) {
console.log("result----"+result) // it returns undefined
if (!err)
return context.sendJson(result, 404);
})
;

This code work in my case while i update value in the table in mongodb i did this code in playframe work for java . Hope it also help in you case.
MongoClient mongo=new MongoClient("localhost",27017);
/*mongo.setWriteConcern(WriteConcern.JOURNALED);*/
DB db = mongo.getDB("webportal");
DBCollection coll=db.getCollection("userdb");
//ObjectId id= new ObjectId(userid);
BasicDBObject doc2 = new BasicDBObject();
doc2.put("_id",userid);
BasicDBObject updateDocument = new BasicDBObject();
updateDocument .append("$set", new BasicDBObject("username", username1).append("password", password1).append("email", email1));
coll.update(doc2, updateDocument);

Related

Mongo 3.6.3 java driver aggregate hint - returns undefined field 'hint'

I am trying to pass a hint on an aggregate in MongoDB Java Driver 3.6.3. The aggregate API allows for adding a hint as in:
MongoCollection<Document> coll = database.getCollection("myCollection")
ArrayList<BasicDBObject> docList = new ArrayList<BasicDBObject>();
BasicDBObject hint = new BasicDBObject("$hint","reportjob_customerId_1_siiDocumentAttributes.deleted_1");
MongoCursor<Document> cursor = coll.aggregate(docList).hint(hint).allowDiskUse(batchContext.isAllowDiskUse()).iterator();
I've tried with $hint and hint, but Mongo always returns Command failed with error -1: 'unrecognized field 'hint'
How do I properly send the hint on the aggregate call?
Looks like there is no support to pass the index name directly to hint. So you have pass the index creation document to the hint which you can get by name and use key to get the index document.
MongoCollection<Document> coll = database.getCollection("myCollection");
Bson index = coll.listIndexes().into(new ArrayList<>()).stream().filter(item -> item.getString("name").equals("reportjob_customerId_1_siiDocumentAttributes.deleted_1")).findFirst().get().getString("key");
List<BasicDBObject> docList = new ArrayList<BasicDBObject>();
MongoCursor<Document> cursor = coll.aggregate(docList).hint(index).allowDiskUse(batchContext.isAllowDiskUse()).iterator();
Legacy driver had support for both index name and document.
MongoClient client = new MongoClient();
DB database = client.getDB("myDatabase");
DBCollection coll = database.getCollection("myCollection");
List<BasicDBObject> docList = new ArrayList<BasicDBObject>();
AggregationOptions options = AggregationOptions.builder().allowDiskUse(batchContext.isAllowDiskUse()).build();
DBCursor dbCursor = ((DBCursor) coll.aggregate(docList, options)).hint("reportjob_customerId_1_siiDocumentAttributes.deleted_1");
You can create a jira to have the option to pass index name in the new driver here

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

How to use DBObject Query in distinct function of mongo template?

i want to find distinct value of a field with some Query criteria. my code is..
public List searchservice(String th_type) {
Query query = new Query();
query.addCriteria(Criteria.where("th_type").regex(th_type));
List list = operations.getCollection("doclist").distinct("th_type", query);
return list;
}
in mongo template a distinct function is defined
mongoTemplate.getCollection(collection).distinct(key, query)
bu my code is giving error because i am using simple Query object instead of DBObject Query. how can i use DBObject Query here?
Use a BasicDBObject for this:
public List searchservice(String th_type) {
BasicDBObject dbObject = new BasicDBObject();
dbObject.append("th_type", th_type);
DBCollection dBCollection = operations.getCollection("doclist");
List list = dBCollection.distinct("th_type", dbObject);
return list;
}
UPDATE:
With regex:
BasicDBObject regexQuery = new BasicDBObject();
regexQuery.put("th_type", new BasicDBObject("$regex", th_type));
List list = operations.getCollection("doclist").distinct("th_type",regexQuery);

getting a pojo from a mongo doc using morphia

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));

using findAndModify in mongodb using grails gorm

I need to use findAndModify in my application with grails and mongoDB.
I used this code :
public static String getNextId(DB db, String seq_name) {
String sequence_collection = "seq"; // the name of the sequence collection
String sequence_field = "seq"; // the name of the field which holds the sequence
DBCollection seq = db.getCollection(sequence_collection); // get the collection (this will create it if needed)
// this object represents your "query", its analogous to a WHERE clause in SQL
DBObject query = new BasicDBObject();
query.put("_id", seq_name); // where _id = the input sequence name
// this object represents the "update" or the SET blah=blah in SQL
DBObject change = new BasicDBObject(sequence_field, 1);
DBObject update = new BasicDBObject("$inc", change); // the $inc here is a mongodb command for increment
// Atomically updates the sequence field and returns the value for you
DBObject res = seq.findAndModify(query, new BasicDBObject(), new BasicDBObject(), false, update, true, true);
return res.get(sequence_field).toString();
}
and it work successful. But now I want use findAndModify without native mongodb object, and with using GORM.
Is there any solution for this work?
There is not way to accomplish this without native API, you can however write your code a bit more compact like this:
def collection = Seq.collection
collection.findAndModify([_id: seq_name ], [ "\$inc": [seq:1] ])
Config your DataSource.groovy with db configurations.
Then define a Domain class:
Class Seq{
int seq
}
And use dynamic finder in a sevice:
Class SeqService {
String findAndModify(String seq_name) {
def seqInstance = Seq.get(seq_name)
if(seqInstance){
seqInstance.seq ++
seqInstance.save()
return seqInstance.seq.toString()
}
return '' //instance not found
}
}
Then make a call when you need that action:
def seqService
def id
.......
def result = seqService.findAndModify(id)
....