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
Related
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.
I am new in Mongodb. can anybody tell me any online tool where i can easily convert my sql/ oracle query in mongodb for my java code.
ex:
Simple oracle query:
select * form student where class = "XII" and name="John";
MongoDb Query for java:
db.getCollection("Student", Student.class).find(and(eq("class" , "XII"), eq("name", "John"))).into(new ArrayList<Employee>());
so i want a query builder for java where i can pass the sql/oracle query and i will get Java code for mongodb as Output.
Please suggest some useful .
I don't think if there is any converter available but I will suggest you to learn it by this best free quick course
https://university.mongodb.com/courses/MongoDB/M101J/
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()));
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();
I'm currently learning the BSON java library for mongodb and I'm trying to transform a org.bson.BSONObject into XML in order to transform it with a XSLT stylesheet.
What kind of java types can I find as values in a BSONObject from a Mongodb ? Of course there will be:
BSONObject (internal doc)
java.lang.String
???
what are the others ? BigDecimal and BigInteger ? boolean, int, long, double ? Timestamp.. etc... ??
thanks,
Pierre
Had to search for it too, but according to this mongodb-dev post mapping is done like this:
NULL null
UNDEFINED null
BOOLEAN Boolean
NUMBER Double
NUMBER_INT Integer
NUMBER_LONG Long
SYMBOL String
STRING String
OID mongodb ObjectID
REF DBPointer
DATE Date
REGEX Pattern
BINARY DBBinary
CODE (exception)
ARRAY DBList
OBJECT DBObject or DBRef
TIMESTAMP DBTimestamp
MINKEY String: "MinKey"
MAXKEY String: "MaxKey"
This article on mongodb.org is a good resource for it, too.
Edit: Had a look at the source: org.bson.types.* is having a number of classes for BSON types. org.bson.BSONDecoder is decoding a BSON string and does the mapping listed above.
One alternative way to operate on BSON would be to use Jackson JSON processor; although by default it operates on JSON, there are extensions to use it both on BSON and XML. Since Jackson does data binding, you can bind BSON data into Java POJOs (with bson4jackson) and write out as XML (with jackson-xml-databind).
Transformation would be as simple as:
String xml = xmlMapper.writeValue(bsonMapper.readValue(bsonData, MyPojo.class));
if you have, or can create, MyPojo that maps all properties; or if not by specifying Map.class as the intermediate type to bind to.