Getting GUID from mongodb insert statement using java API - java

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.

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 method for MongoDB collection.save()

I'm having a problem with MongoDB using Java when I try adding documents with customized _id field. And when I insert new document to that collection, I want to ignore the document if it's _id has already existed.
In Mongo shell, collection.save() can be used in this case but I cannot find the equivalent method to work with MongoDB java driver.
Just to add an example:
I have a collection of documents containing websites' information
with the URLs as _id field (which is unique)
I want to add some more documents. In those new documents, some might be existing in the current collection. So I want to keep adding all the new documents except for the duplicate ones.
This can be achieve by collection.save() in Mongo Shell but using MongoDB Java Driver, I can't find the equivalent method.
Hopefully someone can share the solution. Thanks in advance!
In the MongoDB Java driver, you could try using the BulkWriteOperation object with the initializeOrderedBulkOperation() method of the DBCollection object (the one that contains your collection). This is used as follows:
MongoClient mongo = new MongoClient("localhost", port_number);
DB db = mongo.getDB("db_name");
ArrayList<DBObject> objectList; // Fill this list with your objects to insert
BulkWriteOperation operation = col.initializeOrderedBulkOperation();
for (int i = 0; i < objectList.size(); i++) {
operation.insert(objectList.get(i));
}
BulkWriteResult result = operation.execute();
With this method, your documents will be inserted one at a time with error handling on each insert, so documents that have a duplicated id will throw an error as usual, but the operation will still continue with the rest of the documents. In the end, you can use the getInsertedCount() method of the BulkWriteResult object to know how many documents were really inserted.
This can prove to be a bit ineffective if lots of data is inserted this way, though. This is just sample code (that was found on journaldev.com and edited to fit your situation.). You may need to edit it so it fits your current configuration. It is also untested.
I guess save is doing something like this.
fun save(doc: Document, col: MongoCollection<Document>) {
if (doc.getObjectId("_id") != null) {
doc.put("_id", ObjectId()) // generate a new id
}
col.replaceOne(Document("_id", doc.getObjectId("_id")), doc)
}
Maybe they removed save so you decide how to generate the new id.

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

Exists Query for multilple Document in Mongodb using java driver

If we want to check that the record is exists in Collection or not, then there is an operator $exists in Mongodb. But if we want to know multiple records exists in Collection then how can we check that in single query using java driver?
For Example I have two document:
{"key": "val1"}
{"key": "val2"}
Now if I want to check that 'val1' and 'val2' is exist or not then how can we do that in single query using java driver?
Note: here field name is same in both the documents.
You need to use $in operator for that
db.collection.find( { key : { $in : ['val1','val2'] } } );
equivalent java code might like this
List<string> values = new ArrayList<string>();
values.add("val1")
values.add("val2")
BasicDBObject query = new BasicDBObject();
query.put("key", new BasicDBObject("$in", values));
DBCursor cursor = yourcollection.find(query);
am not much of a java guy, this is going to be more or less same.

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.

Categories

Resources