I have one Json array which is consist 2 or 3 json objects, now I need to combine both the json objects into single json object, 1st json object is coming from one method 2nd is coming from another method let me explain with example
response[
{
"id" : 1,
"name" : "Hi",
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
},
{
"Mrng" : 12:00,
"Evening" : 4:00
}
]
},
{
"email" : "abc#gmail.com",
"address" : "abc district"
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
}
]
}
]
then I need output like
response: {
"id" : 1,
"name" : "Hi",
"no.of slots" [
{
"Mrng" : 10:30,
"Evening" : 11:20
},
{
"Mrng" : 12:00,
"Evening" : 4:00
}
],
"email" : "abc#gmail.com",
"address" : "abc district"
}
In no of slots If I have duplicates need to remove or if unique need to combine, any help will be appreciate.
Thanks in advance
You can have a class representing Mrng and Evening properties and override that class's equals and hash methods for comparing for these attributes. Then have a Set and generate instances and put elements to this.
Finally you will get a unique list and have a json string with some little research. This should be done to no.of.slots only
Related
Say I have some documents like this:
{
"name" : "Wendy",
"phone" : "123",
"GroupId" : 1
},
{
"name" : "Tom",
"phone" : "234",
"GroupId" : 1
},
{
"name" : "Sally",
"phone" : "345",
"GroupId" : 3
},
{
"name" : "Bob",
"phone" : "456",
"GroupId" : 3
},
{
"name" : "Cortana",
"phone" : "567",
"GroupId" : 7
}
I'd like to return a list of full-data documents that contains the first occurrence of each distinct GroupId. I'm thinking Aggregation is the best route for a task like this. Here is what I have so far:
MatchOperation matchStage = Aggregation.match(new Criteria());
GroupOperation groupStage = Aggregation.group("GroupId").first("$$CURRENT").as("??");
// I know the above line is semi-nonsensical
Aggregation aggregation = Aggregation.newAggregation(matchStage, groupStage);
// I only need help creating the aggregation object, beyond this is just a MongoOperations aggregate call
It should be noted that I don't necessarily need to use aggregation so if there is a way to achieve this using a simple "find" then I'm okay with that.
I'm a MongoDb noob, sorry if my "have tried" section is not very useful. However, this is what I would want back:
{
"name" : "Wendy",
"phone" : "123",
"GroupId" : 1
},
{
"name" : "Sally",
"phone" : "345",
"GroupId" : 3
},
{
"name" : "Cortana",
"phone" : "567",
"GroupId" : 7
}
Try this. $first helps to get the first occurrence of the data
Aggregation aggregation = Aggregation.newAggregation(
group("GroupId")
.first("name").as("name")
.first("GroupId").as("GroupId")
.first("phone").as("pnone"),
project().andExclude("_id")
).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION_NAME.class), Object.class).getMappedResults();
Working Mongo playground
I'm working with JSON for the first time and my goal is to make an object with the properties Destination, Origin, and Duration from this JSON result (Google Distance Matrix API)
{
"destination_addresses" : [ "123 High St, Los Angeles, CA 90210, USA" ],
"origin_addresses" : [ "800 Lake Dr, Los Angeles, CA 90210, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "2.0 km",
"value" : 1969
},
"duration" : {
"text" : "6 mins",
"value" : 338
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
So far I have been able to correctly store destination and origin using this line
Property data = new Gson().fromJson(json, Property.class);
But I am having a very hard time figuring out how to get the values from inside the nests. Specifically, I'm trying to grab the "text" from duration.
Any help would be greatly apprciated!
First create a container for the surrounding data.
class MainContent
{
public String destination_addresses;
public String bar;
public List<SubContent> subcontent;
}
Then you create a class for the nested data:
class SubContent
{
public String text;
}
The fields in either classes must have the same names as your json object does.
Then simply:
gson.fromJson(jsonData, MainContent.class);
GSON will attempt to reflect the values from the json string into the object.
I'm getting an JSON array as a string value and I need to create a JSON object using that. array code is like this.
{"eventsList" : [
"requestId" : "82334-adf86d-8bac8ef-289c"
events:[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
i try to create an JSON object using folowing code line
SONObject jsonObject = new JSONObject(string);
I'm getting an error when i run this.
org.json.JSONException: Expected a ',' or ']' at character 35
at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
at org.json.JSONArray.<init>(JSONArray.java:143)
at org.json.JSONTokener.nextValue(JSONTokener.java:351)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
Please help me to solve this issue.
There are several mistakes.
After [ a list of comma-separated values is expected, but you have a colon after "requestId". You probably meant for the [ on line 1 to be a {.
Given the last issue, you probably want a comma after "82334-adf86d-8bac8ef-289c"
If you drop your text into an online JSON formatter and validator, such as this one it will point out all your errors.
Problem is here:
...
"requestId" : "82334-adf86d-8bac8ef-289c"
events:...
You forgot some punctuation:
...
"requestId" : "82334-adf86d-8bac8ef-289c",
"events":......
Use this instead this is JSON syntax. All keys are strings.
This is how the String should be;
{"eventsList" : [
{"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
the requestId and event must be like this: {"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":
And also there must be closing } after closing the inner JSONArray ]
hello all i have a collection like this ` "_id" : ObjectId("55dabba974cd60712be24443"),
"entityType" : "1",
"entityCreatedDate" : "08/24/2015 12:07:20 PM",
"nameIdentity" : [
{
"givenNameOne" : "JOY",
"givenNameThree" : "BRAKEL",
"lastName" : "BRAKEL",
"createdDate" : "08/24/2015 12:07:20 PM",
"sourceId" : [
{
"sourceId" : "55dabba974cd60712be24441"
}
]
},
],
Here name identity is a list as well as sourceId. I am trying to update sourceId list in nameIdentityList if it matches the names. My java code is :
Document sourceDocument=new Document("sourceId",sourceId);
mongoDatabase.getCollection("entity").updateOne(new Document("entityId", entityId).append("nameIdentity.givenNameOne","JOY"),
new Document("$push", new Document("nameIdentity.sourceId", sourceDocument)));
` But i am getting exception like java.lang.RuntimeException: com.mongodb.MongoWriteException: cannot use the part (nameIdentity of nameIdentity.sourceId) to traverse the element ({nameIdentity.
If my condition is satisfied i am expecting like this:
`"_id" : ObjectId("55dabba974cd60712be24443"),
"entityType" : "1",
"entityCreatedDate" : "08/24/2015 12:07:20 PM",
"nameIdentity" : [
{
"givenNameOne" : "JOY",
"givenNameThree" : "BRAKEL",
"lastName" : "BRAKEL",
"createdDate" : "08/24/2015 12:07:20 PM",
"sourceId" : [
{
"sourceId" : "55dabba974cd60712be24441"
},
{
"sourceId" : "55dabba974cd60712be24435"
}
]
},
],`
. any suggestions where am i going wrong?
I have multiple names in my nameIdentity, even if the matched document is second or third , sourceId is always being appened to first document. How do i update to specific matched document.
You missed the positional $ operator after the "nameIdentity" field in $push:
Document sourceDocument=new Document("sourceId",sourceId);
mongoDatabase.getCollection("entity").updateOne(
new Document("entityId", entityId).append("nameIdentity.givenNameOne","JOY"),
new Document("$push", new Document("nameIdentity.$.sourceId", sourceDocument))
);
The $push action like other update action modifiers needs to know the "index" of the matched array element to work on. Otherwise the error as you reported occurs.
Platform: MongoDB, Spring, SpringDataMongoDB
I have a collection called "Encounter" with below structure
Encounter:
{ "_id" : "49a0515b-e020-4e0d-aa6c-6f96bb867288",
"_class" : "com.keype.hawk.health.emr.api.transaction.model.Encounter",
"encounterTypeId" : "c4f657f0-015d-4b02-a216-f3beba2c64be",
"visitId" : "8b4c48c6-d969-4926-8b8f-05d2f58491ae",
"status" : "ACTIVE",
"form" :
{
"_id" : "be3cddc5-4cec-4ce5-8592-72f1d7a0f093",
"formCode" : "CBC",
"fields" : {
"dc" : {
"label" : "DC",
"name" : "tc",
},
"tc" : {
"label" : "TC",
"name" : "tc",
},
"notes" : {
"label" : "Notes",
"name" : "notes",
}
},
"notes" : "Blood Test",
"dateCreated" : NumberLong("1376916746564"),
"dateModified" : NumberLong("1376916746564"),
"staffCreated" : 10013,
"staffModified" : 10013
},
}
The element "fields" is represented using a Java Hashmap as:
protected LinkedHashMap<String, Field> fields;
The Key to the hashmap () is not fixed, but generated at run time.
How do I query to get all documents in the collection where "label" = "TC"?
It's not possible to query like db.encounter.find({'form.fields.dc.label':'TC'}) because the element name 'dc' is NOT known. I want to skip that postion and the execute query, something like:
db.encounter.find({'form.fields.*.label':'TC'});
Any ideas?
Also, how do I best use indexes in this scenario?
If fields were an array and your key a part of the sub-document instead:
"fields" : [
{ "key" : "dc",
"label" : "DC",
"name" : "dc"
},
{ "key" : "tc",
"label" : "TC",
"name" : "tc"
}
]
In this case, you could simply query for any sub-element inside the array:
db.coll.find({"form.fields.label":"TC"})
Not sure how you would integrate that with Spring, but perhaps the idea helps? As far as indexes are concerned, you can index into the array, which gives you a multi-key index. Basically, the index will have a separate entry pointing to the document for each array value.