Java - MongoDB - Map Json object as Java Array - java

I've got an XML configuration mapped to a JSON document which has an array of elements, but when there is only one element, the document looks like this:
{
"name" : "test2"
"products" : {
"id" : "prod3"
"value" : "prod_value3"
}
}
{
"name" : "test1"
"products" : [
{
"id" : "prod1"
"value" : "prod_value1"
},
{
"id" : "prod2"
"value" : "prod_value2"
}
]
}
Instead of an array of elements, there is only one element "products"
The JSON is inserted into the MongoDB database and I'm trying to map the "products" as an ArrayList but in the first example, the array returns empty.
My question is: Is there any way to automatically map this case with Java? Maybe a customMapper?

This case in Java is known as overloading methods. Object of some class and array are different types. You can't use one typecast to another etc., but you can use different type of parameter in the method accepting the value.

Related

Update/add a single value to an array in MongoDB - but not as list?

I want to simply add one value to a tuple from MongoDB.
The key is query, and the variable position should be added as consumer-Variable in the tuple with the following code:
MongoCollection<Document> collection = ...
Bson filter = Filters.eq("query", queryName);
Bson update = Updates.addToSet("consumer", position);
collection.findOneAndUpdate(filter, update);
However, when I look into my database, it looks like a list "consumer" : [ NumberLong(88760) ] has been inserted and not a single value, as shown in the producer field:
{ "_id" : ObjectId(...), "query" : "1000", "consumer" : [ NumberLong(88760) ], "producer" : NumberLong(88760) }
I also tried Update.push() with the same result.
How can I add just a single value, without having it as list?
For example, if you need to update only 1 object from the list inside, you can do it in the format as:
.update_one({"_id": ObjectId(_id)}, {"$set": {"i.5": list[2]}})
where "i.5" - 5 index of the list i.

How to have dynamic data type variable in Java data model class?

An API response will send different data type value in different situation. I am using Gson parser to parse json response string.
eg :
1. { "value" : 1 }
2. { "value" : "Hello" }
3. { "value" : { "name" : "name", "email" : "" } }
You can use Map<String, Object> and then manually check where value is digit, String or nested Map

GlobalSecondary index in DynamoDB

I have to create a Global Secondary Index in Dynamo Db. My Primary table structure is below -
{
"primaryId" : "1234" //HashKey
"dummy1" : "kkd",
"dummy2" : "ddd",
"secondObj": [{
"secondObjId" : "1234",
"name" : "1234",
},
{
"secondObjId" : "12345",
"name" : "12345",
}]
}
Now i have to create GlobalSecondary Index based on "secondObjId" as a hashkey. is it possible to create?
I have created it using AWS console but its showing item count 0 and if i am creating GlobalSecondaryIndex using "dumy1" then its showing proper item count.
So my query is that is it possible to create a GlobalSecondayIndex based on a attribute from DynamoDBDocument?
Indexes can be built only on top-level JSON attributes. In addition, range keys must be scalar values in DynamoDB (one of String, Number, Binary, or Boolean).

How to update embedded mongo document using spring mongo data api

I need some help updating property of embedded collection with JSON structure below -
translation
{
"_id" : ObjectId("533d4c73d86b8977fda970a9"),
"_class" : "com.xxx.xxx.translation.domain.Translation",
"locales" : [
{
"_id" : "en-US",
"description" : "English (United States)",
"isActive" : true
},
{
"_id" : "pt-BR",
"description" : "Portuguese (Brazil)",
"isActive" : true
},
{
"_id" : "nl-NL",
"description" : "Dutch (Netherlands)",
"isActive" : true
}
],
"screens" : [
{
"_id" : "caseCodes",
"dictionary" : [
{
"key" : "CS_CAT1",
"parameterizedValue" : "My investigations",
"locale" : "en-US"
},
{
"key" : "MY_INVESTIGATIONS",
"parameterizedValue" : "",
"locale" : "pt-BR"
},
}
]
}
In above structure:
I want to update "parameterizedValue" usinng spring-data-mongo-db API 1.3.4, for screen with _id="caseCodes" and key = "CS_CAT1".
I tried (here 'values' is an collection name for TranslationValue array)
mongoOperations.updateFirst(Query.query(Criteria.where("screens._id")
.is("caseCodes")), new Update().push(
"screens.dictionary.$.values", translationValue),
Translation.class);
but it said, "can't append array to string "dictionary"....
Any pointers or help here? Thanks.
-Sanjeev
There are a few problems with your logic as well as problems with your schema for this type of update.
Firstly what you have are nested arrays, and this causes a problem with updates as described in the documentation for the positional $ operator. What this means is that any condition matching an element of an array on the query side of the update statement will only match the first array index found.
Since you need a specific entry in the inner array you would need to match that as well. But the "catch" says that only the first match will be used in the positional operator so you cannot have both. The query form (if it were possible to work, which it does not) would actually be something like this (native shell):
db.collection.update(
{
"screens._id": "caseCodes",
"screens.dictionary.key": "CS_CAT1"
},
{
"$set": {
"screens.$.dictionary.$.parameterizedValue": "new value"
}
}
)
Now that would "appear" to be more correct than what you are doing, but of course this fails because the positional operator cannot be used more than once. I may just quite stupidly work in this case as it just so happens that the first matched index of the "screens" array (which is 0) happens to be exactly the same as the required index of the inner element. But really that is just "dumb luck".
To illustrate better, what you need to do with these type of updates is already know the indexes of the elements and place those values directly into the update statement using "dot notation". So updating your second "dictionary" element would go like this:
db.collection.update(
{
"screens._id": "caseCodes",
"screens.dictionary.key": "MY_INVESTIGATIONS"
},
{
"$set": {
"screens.0.dictionary.1.parameterizedValue": "new value"
}
}
)
Also noting that the correct operator to use here is $set as you are not appending to either of the arrays, but rather you wish to change an element.
Since that sort of exactness in updates is unlikely to suit what you need, then you should look at changing the schema to accommodate your operations in a much more supported way. So one possibility is that your "screens" data may not possibly need to be an array, and you could change that to a document form like so:
"screens" : {
"caseCodes": [
{
"key" : "CS_CAT1",
"parameterizedValue" : "My investigations",
"locale" : "en-US"
},
{
"key" : "MY_INVESTIGATIONS",
"parameterizedValue" : "",
"locale" : "pt-BR"
},
]
}
This changed the form to:
db.collection.update(
{
"screens.caseCodes.key": "CS_CAT1"
},
{
"$set": {
"screens.caseCodes.$.parameterizedValue": "new value"
}
}
)
That may or may not work for your purposes, but you either live with the limitations of using a nested array or otherwise change your schema in some way.

What is the Java equivalent to a multi dimensional object in Javascript?

I have an Android game in which I want to store levels as a static Java class.
What is the equivalent of the following Javascript object in Java?
var Levels = {
Level1:{
shapes:[
{
bodytype : "dynamic",
h : "50.0000",
nameid : "hofN7-1",
props : {
id : "properties"
},
rotation : "0.0000",
type : "square",
uid : "Av2EZQh",
w : "50.0000",
x : "20.0000",
y : "20.0000"
},
{
bodytype : "dynamic",
h : "50.0000",
nameid : "hofN7-2",
props : {
gravMassScale : "2",
id : "properties",
inertia : "2",
isBullet : true,
torque : "2",
velocity : {
x : "2",
y : "2"
}
}
}
...
If you are looking for something close to how JS stores objects, you can try JSONObject class:
http://json.org/javadoc/org/json/JSONObject.html
Keeping Syntax-to-Syntax mapping aside, from an engineering perspective, I would store levels in a map of Levels like so:
HashMap<String, Level> myLevels = new HashMap<String, Level>();
As the commenters wrote, you can use a Map to create an equivalent object in Java. However, the values in this map are of different types. Some would be Strings. Some would be arrays of some type of Object. Some would be Maps themselves.
The only collection object you could use then is Map<String, Object>, and then you would need to make instanceof checks each time you used it. This would be clumsy.
You could use a JSON binding library, like Jackson. See http://wiki.fasterxml.com/JacksonHome. This has a mode where you create a class, Levels, and annotates its instance variables so Jackson can turn instances into JSON and back. But you need to know your class structure for that. Jackson has a mode where it can use untyped maps.
Finally, you can model Levels by treating it as a tree and using the Composite pattern. You'd have a Node abstract class that holds a name, and concrete subclasses like IntegerNode, StringNode, DoubleNode, MapNode, and ArrayNode.
Take this adjusted version of your JSON and create the classes using jsonschema2pojo:
{
"Levels":{
"shapes":[
{
"bodytype" : "dynamic",
"h" : "50.0000",
"nameid" : "hofN7-1",
"props" : {
"id" : "properties"
},
"rotation" : "0.0000",
"type" : "square",
"uid" : "Av2EZQh",
"w" : "50.0000",
"x" : "20.0000",
"y" : "20.0000"
},
{
"bodytype" : "dynamic",
"h" : "50.0000",
"nameid" : "hofN7-2",
"props" : {
"gravMassScale" : "2",
"id" : "properties",
"inertia" : "2",
"isBullet" : "true",
"torque" : "2",
"velocity" : {
"x" : "2",
"y" : "2"
}
}
}]
}
}
Check JSON for conversion and choose other options as you need them. You can download and use use the converted classes in you Java project.
Hope this helps ... Cheers!

Categories