MongoDB: Cleanly query an object by _id with JavaDriver - java

I'm trying to update a Mongo objet using is _id. However i don't find the proper syntax to make it work using JavaDriver, here is what I last try.
BasicDBObject filtre = new BasicDBObject ("_id", new BasicDBObject("$oid", id_message));
then giving to the coll.update method.
I manage to make my request work from the shh but didn't manage to trasnlate it properly to Java.
(request is something like : db.message.find({"_id" : ObjectId("516a94c4e4b0a315396e4ba3")}); )
`
How do i properly traslate it to Java. (eventually using QueryBuilder)

If you're trying to translate:
db.message.find({"_id" : ObjectId("516a94c4e4b0a315396e4ba3")})
to Java, follow this basic pattern:
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("testDB");
DBCollection messages= db.getCollection("message");
DBObject query = new BasicDBObject("_id", new ObjectId("516a94c4e4b0a315396e4ba3"));
DBObject messageDoc = messages.findOne(query);
The result would be stored in messageDoc.
The documentation for some reason doesn't cover this basic pattern for some reason currently.

Related

Mongodb Java access collection using regex

All of the documents in my collection contain a string field, "sourceTimeStamp" which looks like for example, 2018-11-15T14:20:06. I am trying to come up with a way to get a particular day's worth of data. I can access the data directly from RoboMongo using:
db.getCollection('archive_Nov_15_8pm_2018').find({ "tfms_object.sourceTimeStamp" : { $regex : /^2018-11-25*/}})
This returns many documents. But I need to do this using JAVA so I tried this:
DBCollection collection = db.getCollection(ARCHIVE_COLLECTION);
Pattern pat = Pattern.compile("^2018-11-15.*");
BasicDBObject query = new BasicDBObject("departureTime", pat);
List<BasicDBObject> obj = new ArrayList<BasicDBObject>();
query.put("$and", obj);
However, I get 0 documents returned. Any ideas?

Java MongoDB: querying with numberLong field

How do I query in mongoDB using the mongoDB java driver for a numberLong field?
I tried this according to this SO post: Java Mongodb numberlong query but it does not work.
Query query= new Query();
query.addCriteria(Criteria.where("time").is("NumberLong("+article.getDate()+")"));
I also tried this where article.getDate() has a return type of Long and it does not work:
query.addCriteria(Criteria.where("time").is(article.getDate()));
There is no new NumberLong object within the java driver to use.
https://docs.mongodb.org/manual/core/shell-types/ suggest that one uses NumberLong() wrapper but it is only for the javascript shell, not for java.
MongoClient client = new MongoClient();
MongoDatabase mongoDb = client.getDatabase("test");
MongoCollection<Document> mongoCollection = mongoDb
.getCollection("numberFormatTest");
mongoCollection.drop();
Document smith = new Document("name", "Smith").append("age", 30)
.append("profession", "Programmer")
.append("phoneNo", "9848022338");
Document jones = new Document("name", "Jones").append("age", 30)
.append("profession", "Hacker")
.append("phoneNo", "9000000000000");
printJson(smith);
printJson(jones);
// mongoCollection.insertMany(asList(smith,jones));
System.out.println("Phone number: "
+ Long.valueOf(smith.getString("phoneNo")).longValue());
The above piece of code might work for you. At the moment, I tried with find but it will work for updates as well.
Even in the above link shared by you,NumberLong wrapper saves the field value in string datatype not as a long datatype. The below statement proves it.
"The NumberLong() wrapper accepts the long as a string:"
I think it was just my oversight in this case. The query here actually works:
query.addCriteria(Criteria.where("time").is(article.getDate()));
I had called my object field as "date" instead of "time", which met it did not get picked up when i queried. Changing it as follows made it work properly.
query.addCriteria(Criteria.where("date").is(article.getDate()));

Getting GUID from mongodb insert statement using java API

I am creating a document in mongodb using something like this:
DBCollection coll =<code to get collection>;
WriteResult res = coll.insert(obj, new WriteConcern());
I then want the GUID of the newly inserted thing. Doing a search for obj would work, but that would be not efficient at all.
You aren't setting the write concern correctly, it is better to use the static ones defined in the class. After an insert the document _id can be found in the object you just inserted:
DBCollection coll =<code to get collection>;
DBObject obj = new BasicDBObject("foo",42);
coll.insert(obj, WriteConcern.ACKNOWLEDGED);
System.out.println("New _id:" + obj.get("_id");
I rarely use the WriteResult returned by inserts for anything.

How to specify UUID in mongo $where clause

I have an object that was stored via mongo-java-driver. Object uses java.util.UUID for its _id field. Following is presentation of object via mongo shell:
> db.b.find()
{ "_id" : BinData(3,"zUOYY2AE8WZqigtb/Tqztw==") }
I have a requirement to process searching via $where clause. I use following code to do it:
Mongo m = new Mongo();
DBCollection coll = m.getDB("a").getCollection("b");
coll.save(new BasicDBObject("_id", UUID.randomUUID()));
// ??? - don't know what should be specified
DBObject query = new BasicDBObject("$where", "this[\"_id\"] == " + ???);
coll.find(query).count()
The question is what should I specify instead of ??? to make it work?
Thanks for any help.
My invesigation shown that only one way to do it is rewriting a query in object based way (I mean migration of $where clause part to BasicDBObject based query). In such case mongo-java-driver supports java.util.UUID without any additional effort.

Mongo/Java findAndReplace not working

I have a Mongo collection like this
email{
"isConfirmed" : true/[or false]
"email" : "xxxxxxxxxxx"
}
When I am trying to update the isConfirmed field to true or false, depending on the email which apparently is unique, it takes ages.
The programming language I am using is Java
Here's my code.
List<String> clientEmails = new ArrayList<String>();
Mongo mongoConnection = new Mongo();
DB mongoDatabase = mongoConnection.getDB(DB_NAME);
DBCollection mongoCollection = mongoDatabase.getCollection(COLLECTION_NAME);
int size = clientEmails.size();
for(int i=0;
i
<
size; i++)
{
BasicDBObject query = new BasicDBObject();
System.out.println(clientEmails.get(i).toString());
query.put("email.email", clientEmails.get(i).toString());
BasicDBObject Update = new BasicDBObject("$set", new BasicDBObject("email.isConfirmed", false));
mongoCollection.update(query, Update);
This one takes ages to run through the collection which consists of around 3500 entries]
//mongoCollection.findAndModify(query, Update);
Even findAndModify doesn't work at all, I am not sure if I am missing something here
However, I have tried with the DBcursor, it works but it takes around 3 minutes to run.
// DBCursor cursor = mongoCollection.find(query);
//
// while(cursor.hasNext()){
// BasicDBObject Update = new BasicDBObject("$set", new BasicDBObject("email.isConfirmed", true));
// mongoCollection.update(cursor.next(), Update);
// }
This method takes around 3 minutes. Can someone suggest me of a workaround or something?
Do you have an index on email.email? If not the query has to do a complete collection scan to find the correct document every time you call update.
You also might want to run mongostat for a while to see what else is going on that could be causing the slowdown. mongostat -h will explain what all the fields mean.
If you were using IDE(like Eclipse) download mongo java driver source as well. Set up breakpoint at
mongoCollection.findAndModify(query, Update);
Step into the java driver, actually you could find excatlly cmd string send to mongo. also actual result from mongo db which should give you more information. Also you can copy/paste cmd string and put into mongo shell, and see what happens next.
I got a issue with findAndModify method, by troubleshooting as I said, found I used wrong 'COLLECTION_NAME' in my code.
I'm using mongo v1.8 and java driver v2.5.3, this method works for me.

Categories

Resources