As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Any one help me to create mongo query for deleting where "name" : "gdfgdfgdfg" embedded document
The object stored as below in Mongo db.
{
"_id": ObjectId("50656f33a4e82d3f98291eff"),
"description": "gdfgdfgdfg",
"menus": [
{
"name": "gdfgdfgdfg"**,
"description": "dfgdgd",
"text": "dfgdfg",
"key": "2",
"onSelect": "yyy",
"_id": ObjectId("50656f3ca4e82d3f98291f00")
},
{
"name": "dfg",
"description": "dfgdfgdfgdf",
"text": "dfgdgf",
"key": "1",
"onSelect": "uuuu",
"_id": ObjectId("50656f44a4e82d3f98291f01")
}
]
}
Any one help me, I'm new to Mongo
In the JavaScript shell you can do this:
var query = {"_id": ObjectId("50656f33a4e82d3f98291eff")};
db.collection.update(query, {'$pull':{ menus: {name : 'gdfgdfgdfg'} } });
or use the Id.
db.collection.update(query, {'$pull': { menus: {"_id": ObjectId("50656f3ca4e82d3f98291f00")} } });
With the Java Driver should be something like this:
BasicDBObject query = new BasicDBObject("_id", new ObjectId("50656f33a4e82d3f98291eff"));
BasicDBObject docToRemove = new BasicDBObject("name", "gdfgdfgdfg");
BasicDBObject updateCommand = new BasicDBObject("$pull", new BasicDBObject("menus", docToRemove));
collection.update(query, updateCommand);
Mongo won't let you delete the embedded document. What you have to do is take the object from the collection, delete the one object in the list, and then save it back into the database.
obj = db.collection.findOne({"_id": ObjectId("50656f33a4e82d3f98291eff")});
menus = obj.menus.splice(0,1); // Or some other way to manually delete
// the one item in the list
db.collection.update({"_id": ObjectId("50656f33a4e82d3f98291eff")},
{$set: {menus: menus}});
It's complicated, see here.
EDIT: If you don't know the index, you can try this:
obj = db.collection.findOne({"_id": ObjectId("50656f33a4e82d3f98291eff")});
var i = 0;
for(i=0;i<obj.menus.length;i++) {
if(obj.menus[i].name === "gdfgdfgdfg")
break;
}
menus = obj.menus.splice(i,1);
db.collection.update({"_id": ObjectId("50656f33a4e82d3f98291eff")},
{$set: {menus: menus}});
$conditionArray=array("_id"=>ObjectId("50656f33a4e82d3f98291eff"));
$dataArray=array("description"=>"");
$db->$collectionName->update($conditionArray,array('$unset' =>$dataArray))->limit(1);
Related
I have a json array to work with, like so:
[
{
"id": "12345",
"eauthId": "123451234512345123451234512345",
"firstName": "Jane",
"middieInitial": "M",
"lastName": "Doe",
"email": "janedoe#usda.gov",
"roles": [
{
"id": "CTIS_ROLE_ID",
"name": "A test role for CTIS",
"treatmentName": "Fumigation"
}
]
},
{
"id": "67890",
"eauthId": "678906789067890678906789067890",
"firstName": "John",
"middieInitial": "Q",
"lastName": "Admin",
"email": "johnadmin#usda.gov",
"roles": [
{
"id": "CTIS_ADMIN",
"name": "An admin role for CTIS",
"treatmentName": "System Administration"
}
]
}
]
My task is to find out the user's "roles" --> "name", once match, get that user's email address and sign in using that email address. It seems like a simple task, but it has been really kicking my bottom, since digging into API is new to me. I've tried different libraries (Jackson, RestAssured, Json Simple) and finally GSon. I don't have time to sit and study everything from the scratch. I just needed a quick solution. But it definitely hasn't been quick. Is anyone kind enough to help me out with this. I'd really appreciate it.
closeableHttpResponse = restClient.get(ConfigurationReader.get("base_url") + ConfigurationReader.get("user_endpoint"));
//Status code
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
System.out.println("statusCode = " + statusCode);
String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
Type userListType = new TypeToken<List<Users>>(){}.getType();
List<Users> users = (List<Users>) new Gson().fromJson(responseString, userListType);
Roles roles = new Gson().fromJson(responseString, Roles.class);
it gives me this error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226)
at com.google.gson.Gson.fromJson(Gson.java:932)
The problem with your code is
Type userListType = new TypeToken<List>(){}.getType();
List users = (List) new Gson().fromJson(responseString, userListType);
You are not receiving just a list, you are actually deserializing an array of lists.
So try this:
List[] users = (List[]) new Gson().fromJson(responseString, List[].class);
I'm building an API to retrieve documents from mongodb, mongo has more than 30 million documents, it takes like 45-60 seconds using the below java code to query documents in this structure:
{
"Type": "CUS",
"ID": "01010101",
"Set": [
{
"Group": "Marketing",
"Rule": "Rule_1",
"Ind": "Y",
},
{
"GroupName": "Sales",
"RuleName": "Rule_2",
"Ind": "N",
}
]
}
BasicDBObject query = new BasicDBObject();
query.put("ID", new BasicDBObject("$in", payload.getIds()));
FindIterable<Document> documents = collection.find(query);
for (Document doc : documents) {
// looping through docs and then construct some objects and returns the result to the controller class
}
it looks like it takes too much time on the loop part "for (Document doc : documents)", I'm not sure what's going on, can you please help.
Thanks, and I appreciate it.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I currently use json-simple library in Java to work with JSON objects. Most of the time I get JSON string from some external web service and need to parse and traverse it. Even for some not too complex JSON objects that might be pretty long typing exercise.
Let's assume I got following string as responseString:
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
],
"title": "some company",
"headcount": 3
}
To get last name of 3d employee I'll have to:
JSONObject responseJson = (JSONObject) JSONValue.parse(responseString);
JSONArray employees = (JSONArray) responseJson.get("employees");
JSONObject firstEmployee = (JSONObject) employees.get(0);
String lastName = (String) firstEmployee.get("lastName");
Something like that at least. Not too long in this case, but might get complicated.
Is there any way for me (maybe switching to some other Java library?) to get more streamlined fluent approach working?
String lastName = JSONValue.parse(responseString).get("employees").get(0).get("lastName")
I can't think of any auto-casting approach here, so will appreciate any ideas.
Try Groovy JsonSlurper
println new JsonSlurper().parseText(json).employees[0].lastName
Output:
Doe
But best solution is JsonPath - with typing
String name = JsonPath.parse(json).read("$.employees[0].lastName", String.class);
System.out.println(name);
I am using Java API for CRUD operation on elasticsearch.
I have an typewith a nested field and I want to update this field.
Here is my mapping for the type:
"enduser": {
"properties": {
"location": {
"type": "nested",
"properties":{
"point":{"type":"geo_point"}
}
}
}
}
Of course my enduser type will have other parameters.
Now I want to add this document in my nested field:
"location":{
"name": "London",
"point": "44.5, 5.2"
}
I was searching in documentation on how to update nested document but I couldn't find anything. For example I have in a string the previous JSON obect (let's call this string json). I tried the following code but seems to not working:
params.put("location", json);
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location = location").setScriptParams(params).execute().actionGet();
I have got a parsing error from elasticsearch. Anyone knows what I am doing wrong ?
You don't need the script, just update it.
UpdateRequestBuilder br = client.prepareUpdate("index", "enduser", "1");
br.setDoc("{\"location\":{ \"name\": \"london\", \"point\": \"44.5,5.2\" }}".getBytes());
br.execute();
I tried to recreate your situation and i solved it by using an other way the .setScript method.
Your updating request now would looks like :
client.prepareUpdate(index, ElasticSearchConstants.TYPE_END_USER,id).setScript("ctx._source.location =" + json).execute().actionGet()
Hope it will help you.
I am not sure which ES version you were using, but the below solution worked perfectly for me on 2.2.0. I had to store information about named entities for news articles. I guess if you wish to have multiple locations in your case, it would also suit you.
This is the nested object I wanted to update:
"entities" : [
{
"disambiguated" : {
"entitySubTypes" : [],
"disambiguatedName" : "NameX"
},
"frequency" : 1,
"entityType" : "Organization",
"quotations" : ["...", "..."],
"name" : "entityX"
},
{
"disambiguated" : {
"entitySubType" : ["a", "b" ],
"disambiguatedName" : "NameQ"
},
"frequency" : 5,
"entityType" : "secondTypeTest",
"quotations" : [ "...", "..."],
"name" : "entityY"
}
],
and this is the code:
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(indexName);
updateRequest.type(mappingName);
updateRequest.id(url); // docID is a url
XContentBuilder jb = XContentFactory.jsonBuilder();
jb.startObject(); // article
jb.startArray("entities"); // multiple entities
for ( /*each namedEntity*/) {
jb.startObject() // entity
.field("name", name)
.field("frequency",n)
.field("entityType", entityType)
.startObject("disambiguated") // disambiguation
.field("disambiguatedName", disambiguatedNameStr)
.field("entitySubTypes", entitySubTypeArray) // multi value field
.endObject() // disambiguation
.field("quotations", quotationsArray) // multi value field
.endObject(); // entity
}
jb.endArray(); // array of nested objects
b.endObject(); // article
updateRequest.doc(jb);
Blblblblblblbl's answer couldn't work for me atm, because scripts are not enabled in our server. I didn't try Bask's answer yet - Alcanzar's gave me a hard time, because I supposedly couldn't formulate the json string correctly that setDoc receives. I was constantly getting errors that either I am using objects instead of fields or vice versa. I also tried wrapping the json string with doc{} as indicated here, but I didn't manage to make it work. As you mentioned it is difficult to understand how to formulate a curl statement at ES's java API.
A simple way to update the arraylist and object value using Java API.
UpdateResponse update = client.prepareUpdate("indexname","type",""+id)
.addScriptParam("param1", arrayvalue)
.addScriptParam("param2", objectvalue)
.setScript("ctx._source.field1=param1;ctx._source.field2=param2").execute()
.actionGet();
arrayvalue-[
{
"text": "stackoverflow",
"datetime": "2010-07-27T05:41:52.763Z",
"obj1": {
"id": 1,
"email": "sa#gmail.com",
"name": "bass"
},
"id": 1,
}
object value -
"obj1": {
"id": 1,
"email": "sa#gmail.com",
"name": "bass"
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a JSON coming from server as below
{
"XXXX": {
"type": "RSS",
"value": ""
},
"YYYY": {
"type": "String",
"value": ""
},
"ZZZZ": {
"type": "String",
"value": ""
}
}
Now I need to add the String value in fields of all XXXX, YYYY, and ZZZZ.
I'm using eclipse and I need to change the value of "value" in XXXX and YYYY and ZZZZ and I need to add the field
{
"MMMM": {
"type": "Image",
"value": "a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"
}
}
After ZZZZ. Please let me know how to do it.
Try this
String jsonstring="{
"XXXX": {
"type": "RSS",
"value": ""
},
"YYYY": {
"type": "String",
"value": ""
},
"ZZZZ": {
"type": "String",
"value": ""
}
}";
JSONObject object=new JSONObject(jsonstring);
JSONObject childobject=object.getJSONObject("XXXX");
JSONObject modifiedjson=new JSONObject();
modifiedjson.put("type",childobject.get("type"));
modifiedjson.put("value","newvalue"); // Add new value of XXXX here
//
JSONObject mmjson=new JSONObject();
mmjson.put("type","image");
mmjson.put("value","a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"); // Add new value of MMM here
JSONObject newjson=new JSONObject();
newjson.put("MMMM",mmjson.toString());
newjson.put("XXXX",modifiedjson.toString());
newjson.put("YYYY",object.get("YYYY"));
newjson.put("ZZZZ",object.get("ZZZZ"));
I think you meant
{"XXXX":
{"type":"RSS","value":"},
"YYYY (mins)":{"type":"String","value":""},
"ZZZZ":{"type":"String","value":""}
is the JSON you get from server. You can always get the JSONObject.toString and edit it as required and then do something like,
JSONObject obj = new JSONObject(myString);
If you need to add a key value to JSON you may try,
JSONObject value = new JSONObject();
value.put("key","value");
value.put("key","value");//add all the field you want for ZZZZ.
obj.put("ZZZZ",value);
If it is a string, you can just search for the specified values and concat the new string.
If it is a JSON Object, you could add new Values to the JSON Object and search for the values you want to manipulate and set them new.
What are you doing at the moment? Can you show us some code, so we know, where exactly you have the problem? And show, how you are accessing the JSON in this code, please.
User Java String replacement method to replace string.
Take you Json as a string then replace value via string replacement method.
Here is small example.
String replaceSample = "This String replace Example shows how to replace one char from
String newString = replaceSample.replace('r', 't');
Thanks.
var source={
"XXXX": {
"type": "RSS",
"value": ""
},
"YYYY": {
"type": "String",
"value": ""
},
"ZZZZ": {
"type": "String",
"value": ""
}
}
And element you wanted to add
var element={
"type": "Image",
"value": "a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"
};
You can do with below script,
source["MMMM"]=element;
or
source.MMMM=element;
You can do all operations in JavaScript itself.
Lets store the date coming from server into variable a:
var a = {
"XXXX":{"type":"RSS","value":"},
"YYYY (mins)":{"type":"String","value":""},
"ZZZZ":{"type":"String","value":""}
}
To change the value:
a['XXXX']['value'] = 'new_value1';
a['YYYY']['value'] = 'new_value2';
a['ZZZZ']['value'] = 'new_value3';
To add a field:
a["MMMM"] = {"type":"Image","value":"a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"}}