I have a few entries in a mongodb database. They have binary _ids. If I query with a mongo client like robomongo I'm able to find the entry I'm looking for:
db.getCollection('comment').find({"_id" : new BinData(0,"nCgNlWhzJM9/lHDVQmXQrg==")})
However, I'm having serious issues with doing the same in java. Here is what I'm trying to do:
final MongoCollection<Document> mongoCollection = mongoDatabase.getCollection("comment");
mongoCollection
.find(eq("_id", new Binary((byte) 0, "nCgNlWhzJM9/lHDVQmXQrg==".getBytes(StandardCharsets.UTF_8))))
.first()
Sadly this is not working. Trying to find an item with a string type works (like eq("author", "someone) ).
Your _id value nCgNlWhzJM9/lHDVQmXQrg== is shown Base64 encoded, so your java query should be written:
Document doc = mongoCollection
.find(eq("_id", new Binary((byte) 0, Base64.getDecoder().decode("nCgNlWhzJM9/lHDVQmXQrg=="))))
.first();
To decode the key before using it to create the binary filter.
Related
How do you retrieve the most recently added Document from a MongoCollection using Java? Most of the existing references describe how to do this in v2. How do you do this in v3.3?
I suppose it has something to do with the find(Bson filter) method. How do you specify the Bson filter and how do you convert a FindIterable to a Document?
For this you can use the $natural sort order. On your MongoDb query specify the sort :
{ $natural : -1}
Then limit by 1 and you have the correct document
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()));
I am new to JAVA and MONGODB and have been learning both to try and understand if these technologies would meet my requirements for a product.
I am currently stuck in a point where I am not able to insert documents(records) from JAVA into my MONGODB collection.
I am using the new MONGODB version 3.0.
Code so far
MongoCollection<Document> coll = db.getCollection("Collection");
String json = "{'class':'Class10', 'student':{'name':'Alpha', 'sex':'Female'}, {'name':'Bravo', 'sex':'Male'}}";
I have found code to convert this to a DBObject type.
DBObject dbObject = (DBObject)JSON.parse(json);
But I guess the new version of MONGODB does not have the insert method but instead has the insertOne method.
coll.insertOne() requires that the input be in the Document format and does not accept the DBObject format.
coll.insertOne((Document) dbObject);
gives the error
com.mongodb.BasicDBObject cannot be cast to org.bson.Document
Can someone help me with the right type casting and give me a link where I could find and learn the same?
Regards.
Use the static parse(String json) method that's defined in the Document class.
The problem is that you are using an older
version(BasicDBObject) that is not compatible with version 3.0.
But there is a way for 2.0 users to use BasicDBObject.An overload of
the getCollection method allows clients to specify a different class
for representing BSON documents.
The following code must work for you.
MongoCollection<BasicDBObject> coll = db.getCollection("Collection", BasicDBObject.class);
coll.insertOne(dbObject);
I used google gson for convert pojo to json, and this is work perfect.
private final MongoCollection<Document> collection;
//my save
String json = gson.toJson(data);//data is User DTO, just pojo!
BasicDBObject document = (BasicDBObject) JSON.parse(json);
collection.insertOne(new Document(document));
Java mongodb driver version is 3.4.2
Using the MongoDB Java API, I have not been able to successfully locate a full example using text search. The code I am using is this:
DBCollection coll;
String searchString = "Test String";
coll.createIndex(new BasicDBObject ("blogcomments", "text"));
DBObject q = start("blogcomments").text(searchString).get();
The name of my collection that I am performing the search on is blogcomments. creatIndex() is the replacement method for the deprecated method ensureIndex(). I have seen examples for how to use the createIndex(), but not how to execute actual searches with the Java API. Is this the correct way to go about doing this?
That's not quite right. Queries that use indexes of type "text" can not specify a field name at query time. Instead, the field names to include in the index are specified at index creation time. See the documentation for examples. Your query will look like this:
DBObject q = QueryBuilder.start().text(searchString).get();
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.