Update nested array list in mongodb java - java

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.

Related

Combine Two Json Objects in java which is in single json array

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

Error in Creating JSON 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 ]

How do I get a specific element of the array in mongoDB?

I want to get a specific element of the array and through the responsaveis.$ (daniela.morais#sofist.com.br) but there is no result, there is problem in my syntax?
{
"_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
"agencia" : "Abc",
"instancia" : "dentsuaegis",
"cliente" : "Samsung",
"nomeCampanha" : "Serie A",
"ativa" : true,
"responsaveis" : [
"daniela.morais#sofist.com.br",
"abc#sofist.com.br"
],
"email" : "daniela.morais#sofist.com.br"
}
Syntax 1
mongoCollection.findAndModify("{'responsaveis.$' : #}", oldUser.get("email"))
.with("{$set : {'responsaveis.$' : # }}", newUser.get("email"))
.returnNew().as(BasicDBObject.class);
Syntax 2
db.getCollection('validatag_campanhas').find({"responsaveis.$" : "daniela.morais#sofist.com.br"})
Result
Fetched 0 record(s) in 1ms
The $ positional operator is only used in update(...) or project calls, you can't use it to return the position within an array.
The correct syntax would be :-
Syntax 1
mongoCollection.findAndModify("{'responsaveis' : #}", oldUser.get("email"))
.with("{$set : {'responsaveis.$' : # }}", newUser.get("email"))
.returnNew().as(BasicDBObject.class);
Syntax 2
db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais#sofist.com.br"})
If you just want to project the specific element, you can use the positional operator $ in projection as
{"responsaveis.$":1}
db.getCollection('validatag_campanhas').find({"responsaveis" : "daniela.morais#sofist.com.br"},{"responsaveis.$":1})
Try with this
db.validatag_campanhas.aggregate(
{ $unwind : "$responsaveis" },
{
$match : {
"responsaveis": "daniela.morais#sofist.com.br"
}
},
{ $project : { responsaveis: 1, _id:0 }}
);
That would give you all documents which meets that conditions
{
"result" : [
{
"responsaveis" : "daniela.morais#sofist.com.br"
}
],
"ok" : 1
}
If you want one document that has in its responsaveis array the element "daniela.morais#sofist.com.br" you can eliminate the project operator like
db.validatag_campanhas.aggregate(
{ $unwind : "$responsaveis" },
{
$match : {
"responsaveis": "daniela.morais#sofist.com.br"
}
}
);
And that will give you
{
"result" : [
{
"_id" : ObjectId("54fa059ce4b01b3e086c83e9"),
"agencia" : "Abc",
"instancia" : "dentsuaegis",
"cliente" : "Samsung",
"nomeCampanha" : "Serie A",
"ativa" : true,
"responsaveis" : "daniela.morais#sofist.com.br",
"email" : "daniela.morais#sofist.com.br"
}
],
"ok" : 1
}
Hope it helps

Java query for mongodb to find documents where list size is less than n

I'm trying to find all of the documents in my db where the the size of my "states" list only contains one state but I'm struggling with the syntax of the java code.
My db looks like this:
{ "_id" : 13218 , "country" : { "MY" : 11 , "US" : 4} , "state" : { "WA" : 4 }}
{ "_id" : 95529 , "country" : { "US" : 6 } , "state" : { "MI" : 6 }}
{ "_id" : 22897 , "country" : { "US" : 4 } , "state" : { "CA" : 2 , "TX" : 1 , "WY" : 1 }}
What I want to do is print out every "_id" found from the US that only has a single state. So, the only "_id" that'd be returned here is 95529.
here is the relevant portion of code:
DBObject query = new BasicDBObject("country.US", new BasicDBObject("$gt", 4));
//query.put("state.2", new BasicDBObject("$exists", true));
//This is my attempt at checking the list length but it doesn't work
DBCursor dbCursor = dBcollection.find(query);
while (dbCursor.hasNext()){
DBObject record = dbCursor.next();
Object _id= record.get("_id");
Object state= record.get("state");
System.out.println(_id + "," + state);
}
current output looks like this:
95529, { "MI" : 6 }
22897, { "CA" : 2 , "TX" : 1 , "WY" : 1 }
The essential problem you have here is that your data is not in fact a "list". As a "hash" or "map" which is what it really is there is no concept of "length" in a MongoDB sense.
You would be better off changing your data to use actual "arrays" which is what a list actually is:
{
"_id" : 13218 ,
"country" : [
{ "code": "MY", "value" : 11 },
{ "code": "US", "value" : 4 },
],
"state" : [{ "code": "WA", "value" : 4 }]
},
{
"_id" : 95529 ,
"country" : [{ "code": "US", "value" : 6 }],
"state" : [{ "code": "MI", "value" : 6 }]
},
{
"_id" : 22897 ,
"country" : [{ "code": "US", "value" : 4 }],
"state" : [
{ "code": "CA", "value" : 2 },
{ "code": "TX", "value" : 1 },
{ "code": "WY", "value" : 1 }
]
}
Then getting those documents that only have a single state is a simple matter of using the $size operator.
DObject query = new BasicDBObject("country",
new BasicDBObject( "$elemMatch", new BasicDBObject(
"code", "US").put( "value", new BasicDBObject( "$gt", 4 )
)
);
query.put( "state": new BasicDBObject( "$size", 1 ) );
This ultimately gives you a lot more flexibilty in issuing queries as you don't need to specify the explicit "key" in each query. Also as noted, there is a concept of length here that does not otherwise exist.
If you keep your data in it's current form then the only way to do this is with the JavaScript evaluation of the $where operator. That is not very efficient as the interpreted code needs to be run for each document in order to determine if the condition matches:
DBObject query = new BasicDBObject("country.US", new BasicDBObject("$gt", 4));
query.put("state", new BasicDBObject( "$type", 3 ));
query.put("$where","return Object.keys( this.state ).length === 1");
Also using the $type operator in order to make sure that "state" is actually present and an "Object" that is expected. So possible, but not a really great idea do to performance.
Try to change your document structure as it will make other sorts of queries possible without using JavaScript evaluation.

Mongo query inside Hashmap with unknown hash key

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.

Categories

Resources