MongoDB+Java - parsing JSON via com.mongodb.util.JSON.parse - java

I am using com.mongodb.util.JSON.parse to parse a JSON file to DBObject. How do I specify dates, refs, and objects IDs in the JSON file?

Dates : { myDate: {$date: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" } } // Date in the mentioned ISODate string format.
Refs : { myRef : { $ref : <collname>, $id : <idvalue>[, $db : <dbname>] } } // collname is collection name, idvalue is the _id of the referred document and optionally dbname is the database the document is in.
ObjectIds : { _id : {$oid: "4e942f36de3eda51d5a7436c"} }

Related

Mongodb query to find all the keys by its values

I new to mongodb. I have a doc which is look like
So I want to fire a query for object "users" which gives me all the key names who values is true.
Please answer in java
You can try below aggregation pipeline in 3.4.4 version.
Change the users embedded document into array of key value pairs using $objectToArray followed by $filter + $map to extract the keys for matching value.
db.collection.aggregate([
{
$project: {
keys: {
$map: {
input: {
$filter: {
input: {$objectToArray: "$users"},
as: "resultf",
cond: {
$eq: ["$$resultf.v", true]
}
}
},
as: "resultm",
in: "$$resultm.k"
}
}
}
}
])
Following query will give you all the users keys whose value is true in array format -
db.collectionName.find({},{users:1}).map(function(myDoc){
var names = [];
for (var key in myDoc.users) {
if(myDoc.users[key]){
names.push(key);
}
}
return names;
});

Mongo Java Driver - How to update a subdocument into an array element

How could I update a specific field in subdocument of array element ?
My question is similar to the following below, but in my case I need to update just a subdocument value.
MongoDB: How do I update a single subelement in an array, referenced by the index within the array?
I have the following documento model :
{
_id : "xpto",
other_stuff ... ,
templates : [
{
templateId:"template-a"
body: {
en_US:"<p>Hello World!</p>"
}
},
{
templateId:"template-b"
body: {
es_ES:"<p>Holla !</p>"
}
}
]
}
So, In mongodb shell the following statement works perfectly for me:
db.apiClient.update({"_id":"xpto","templates.templateId":"template-b"}, {$set:{"templates.$.body.es_ES":"<h1>Gracias !</h1>"}})
However , when i try to do it with Mongo Java Driver , I get an IllegalArgumentException.
BasicDBObject selectQuery = new BasicDBObject("_id", "xpto");
selectQuery.put("templates.templateId", "template-b");
BasicDBObject updateQuery = new BasicDBObject();
for(String locale : template.getBody().keySet()) {
String updateBodyLocaleExpression = new StringBuilder()
.append("templates.$.body.").append(locale).toString();
String updateBodyLocaleValue = template.getBody().get(locale);
updateQuery.put(updateBodyLocaleExpression, updateBodyLocaleValue);
}
updateQuery.put("$set", updateQuery);
getCollection(COLLECTION_NAME).update(selectQuery, updateQuery, true, true);
It throws the following exception :
Caused by: java.lang.IllegalArgumentException: Invalid BSON field name templates.$.body.es_ES
at org.bson.AbstractBsonWriter.writeName(AbstractBsonWriter.java:494)
at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:127)
at com.mongodb.DBObjectCodec.encode(DBObjectCodec.java:61)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:63)
at org.bson.codecs.BsonDocumentWrapperCodec.encode(BsonDocumentWrapperCodec.java:29)
at com.mongodb.connection.RequestMessage.addDocument(RequestMessage.java:253)
at com.mongodb.connection.RequestMessage.addCollectibleDocument(RequestMessage.java:219)
at com.mongodb.connection.UpdateMessage.encodeMessageBodyWithMetadata(UpdateMessage.java:77)
at com.mongodb.connection.RequestMessage.encodeWithMetadata(RequestMessage.java:160)
at com.mongodb.connection.WriteProtocol.execute(WriteProtocol.java:85)
Is something wrong with my code ?
Thanks.
Yes. You construct wrong updateQuery. You put fields templates.$.body... in the BasicDbObject and then add same document into $set field into itself. MongoDB tries to update field templates.$.body. and here $ is the part of the field name instead of operator.
Here is working example:
//List is for testing purposes only
List<String> locales = Arrays.asList("en_US", "en_UK");
Document query = new Document("_id", "xpto")
.append("templates.templateId", "template-b");
Document updateQuery = new Document();
for (String locale : locales) {
updateQuery.put("templates.$.body." + locale, "<pre>Updated " + locale + "</pre>");
}
collection.updateOne(query, new Document("$set", updateQuery));
Document is almost the same as BasicDbObject but more general.

Get ISO date object from mongoDb using Java

I want to get Iso date object value from mongodb collection.
below is my mongodb Collections
{
"_id" : ObjectId("55c4657f036499106cf73fae"),
"from" : "Administrator",
"subject" : " Exception details :: InternalSession",
"dateTs" : ISODate("2015-08-07T07:59:59.172Z")
}
i want to get dateTs column value i.e iSODate.
Below is my java code:
while (requestsCursor.hasNext()) {
DBObject dbObject = requestsCursor.next();
JSONArray toArr = new JSONArray();
String from = (String) (dbObject.containsField(FROM) ? dbObject.get(FROM) : "-");
ISO8601DateFormat dT = (ISO8601DateFormat) dbObject.get("dateTs");
System.out.println("dateTs : "+dT);
}
I am getting null value
please Suggest ..

Extract field value from mongodb BasicDBobject

I am developing simple web application to learn jsp, mongodb, html. I have created an simple registration form in jsp which takes Name, Address and MobileNo information from user and insert it into mongodb, Now I want to retrieve this stored data and put value of every field in individual string variable.
Ex:
Name: varun; Address: Nagpur; MobileNo: 1234567890
Above data is stored in mongodb as:
{
"_id" : ObjectId("5259bacea6f8b1c4cd3431d3"),
"Name" : "varun",
"Address" : "nagpur",
"MobileNumber" : "1234567890"
}
Retrieved in jsp as follows:
MongoClient mongoC = new MongoClient(new ServerAddress("Localhost",27017));
DB database = mongoC.getDB("dbfrnzout");
DBCollection collec1 = database.getCollection("coll");
DBObject dock= collec1.findOne();
out.println(dock);
This code print one record as json document and I want to store value associated with every
field in individual string variable, something like this:
String s1 = varun ie. value of field Name
Need some guidance.
DBObject implements the Map<String, Object> interface so you should be able to do something like:
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
Be careful with the casts and make sure you are certain of the type and existence of each field. For numeric values I strongly recommend casting to a Number instead of Integer since MongoDB will re-cast values to a Long or Double at the weirdest times.
HTH, Rob.
Edit: If you are iterating over the results of a query you will have to inspect each document as it is returned from the iterator
DBCollection collec1 = database.getCollection("coll");
for( DBObject dock : collec1.find() ) {
String name = (String) dock.get( "Name" );
String address = (String) dock.get( "Address" );
String mobileNumber = (String) dock.get( "MobileNumber" );
// Do Something...
}
Do something like this to get an object from a cursor
while (cursor.hasNext())
dbObject o = cursor.next()

How to store a string value in mongo db as an json object?

I am getting the data from the UI as follows, all the below input data are strings.
cust_id : temp001
cust_chart_id : testing
default_chart : false
chart_pref_json : {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20} }
I am trying to store chart_pref_json in mongodb. This chart_pref_json object is actually stored in db as a string below,
{ "_id" : ObjectId("50aca4caf5d0b0e4d31ef239"), "cust_id" : "temp001", "cust_chart_id" : "testing", "default_chart" : "false", "created_at" : NumberLong("1353491658551"), **"chart_pref_json" : "{range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20}" }**
But i actually want this chart_pref_json to be stored as an json object as below.
{ "_id" : ObjectId("50aca4caf5d0b0e4d31ef239"), "cust_id" : "temp001", "cust_chart_id" : "testing", "default_chart" : "false", "created_at" : NumberLong("1353491658551"), **"chart_pref_json" : {range:6m,chart_type:candlestick,indicators:{},period:Daily,futurepadding:20} }**
Can any one help me out on this issue.
When you have the JSON code as a string, you first have to parse the JSON code and then convert the resulting JSON object to a BSON object.
You can use the class com.mongodb.util.JSON which comes with MongoDB. Here is a tutorial.
Since this is a Java question, here's how you insert a JSON by using the MongoDB Java driver:
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
public class Main {
public static void main(String[] args) {
MongoClientURI uri = new MongoClientURI("mongodb://myuser:mypsw#localhost:27017/mydb");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase("mydb");
String json =
"{\n" +
" \"_id\" : \"MyId\",\n" +
" \"foo\" : \"bar\"\n" +
"}";
db.getCollection("mycoll").insertOne(Document.parse(json));
}
}
Before you set it as a field in your application, you need to use your language's JSON decoding abilities to encode it as an object. In PHP, you would do that like:
$db->collection->insert( array(
'cust_id' => 'temp001',
… your other fields …
'chart_pref' => json_decode( $varContainingJson )
) );
For Java, the following example will help:
BasicDBObject obj = JSON.parse( varContainingJson );
Which is described at https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/Y3KyG_ZSfJg

Categories