I am quite new to Spring Boot and MongoDB. I am trying to update the availability for a specific user within the user array. The issue is that I am trying to find a specific username for example: "Mark" and update that entry only. However, it could be under any index of the array, and I'm not quite sure how write that in the query statement.
The structure of my data in mongoDB:
{
"name": "test meeting",
"url": "temporary_url",
"timezone": "pacific",
"startTime": 8,
"endTime": 21,
"users": [
{
"username": "Mark",
"password": "Caddy",
"availability": { << TRYING TO UPDATE THIS
//array of objects
}
},
{
"username": "Bill",
"password": "Bobby",
"availability": {
//array of objects
}
}
],
"_class": "com.dcproduction.meetapp.classes.Meeting"
}
Below is my attempt to make it work. It works if I substitute an index for [WHAT GOES HERE] such as '0', but the point of this query is that I wouldn't normally know which index the name would fall under:
Query query = new Query();
query.addCriteria(
new Criteria().andOperator(
Criteria.where("name").is("test meeting"),
Criteria.where("users.[WHAT GOES HERE?]username").is("Mark")));
Update testUpdate = new Update();
testUpdate.set("users[WHAT GOES HERE].availability", some_data);
UpdateResult updateResult = mongoTemplate.updateFirst(query, testUpdate, Meeting.class);
Any help would be appreciated, thanks!
You could use identifiers as mentioned here: https://www.mongodb.com/docs/manual/reference/operator/update/positional-filtered/
which would be of the form:
query.addCriteria(
Criteria.where("users._username").is("Mark")
);
update.set("users.$[selector].availability", some_data)
.filterArray(Criteria.where("selector._username").is("Mark"));
Related
I have a admin app written with Java to be able to manage my users
I created a custom json
This is what my JSON looks like
[
{
"userId": 1,
"email": "user1#gmail.com",
"sponsorship": true,
"create": 274
},
{
"userId": 2,
"email": "user2#gmail.com",
"sponsorship": false,
"create": 201
},
{
"userId": 3,
"email": "user3#gmail.com",
"sponsorship": false,
"create": 189
}
]
In my List I just display email address
Now my problem, for example if I click on the List which contains the email user1#gmail.com, I want to display in a Dialog the data related to this email, i.e. the userId, sponsorship and create
How can I retrieve the other values using the email?
I couldn't find anything about it on the internet
When reading your json file, you need to make it understandable.
There is an example of making it understandable in the link below.
You have to write a condition after these procedures. The condition should be:
for(int i=0; i< employeeList.size;i++){
if(employeeList[i].email.equals("user3#gmail.com")){
//the person you are looking for
var person = employeeList[i];
}
}
https://howtodoinjava.com/java/library/json-simple-read-write-json-examples/
[{
"_id": {
"$oid": "5ee227d69dba6729ca8938fc"
},
"uuid": "4e9be217-a2c7-490f-86b7-2d46a69980a3",
"locks": {
"furnace_1591879638": {
"type": "FURNACE",
"location": {
"world": "world",
"x": -33,
"y": 73,
"z": -227
},
"created": "Thu Jun 11 14:47:18 CEST 2020",
"peopleWithAccess": []
},
"chest_1591903237541": {
"type": "CHEST",
"location": {
"world": "world",
"x": -36,
"y": 73,
"z": -224
},
"created": "Thu Jun 11 21:20:37 CEST 2020",
"peopleWithAccess": []
}
}
},{
"_id": {
"$oid": "5ee2864622c67536a249fb0a"
},
"uuid": "6fc93f76-b03b-4af3-a679-ac53cafdb288",
"locks": {}
}]
Hi,
I just stared with MongoDB and I was used to working with MySQL so this is really confusing for me. I've been trying to delete a object from an array but unsuccessfully. I tried this:
getMongoManager().getDatabase().getCollection("players").updateOne(new Document("uuid", player.getUniqueId().toString()),
new Document("$unset", "locks." + id))
That gave me an error Modifiers operate on fields but we found type string instead.
How would I delete for exmaple object furnace_1591879638 from player with uuid 4e9be217-a2c7-490f-86b7-2d46a69980a3 in Java?
Unfortunately, we cannot use the $unset operator to remove objects from an array, since the operator can only remove whole fields. For removing and inserting in an array, we are using $pull and $push.
I would recommend you to look up, both Bson Updates and Filters class because they are making it way easier, instead of using the operators (At least for the mongodb driver version 3.8 or higher; I do not know if older versions support Bson).
With the help of these classes, you could extend your
MongoManager
class and try something like this:
public void pullByFilter(String queryField, Object queryValue, String arrayName, Object value) {
MongoCollection<Document> collection = getCollection("players");
Bson update = Updates.pullByFilter(Filters.eq(arrayName, value));
collection.updateOne(Filters.eq(queryField, queryValue), update);
}
This method should remove the specified value from the array.
Just for clearance: the queryField and queryValue parameters are used to identify the document (for you, the queryField should be "uuid" and the queryValue should be the players UUID as string).
Lastly, I think the method you tried with the $unset operator is giving you an error because you need to specify a new Document after the operator.
This:
getMongoManager().getDatabase().getCollection("players").updateOne(new Document("uuid", player.getUniqueId().toString()),
new Document("$unset", "locks." + id))
should rather be:
getMongoManager().getDatabase().getCollection("players").updateOne(new Document("uuid", player.getUniqueId().toString()),
new Document("$unset", new Document("locks", id)))
Also, a good tutorial for updating documents can be found here.
I am using couchbase Community Edition 5.0.1 and java-client 2.7.4. I want to store the following nested json object into couchbase. If I want to update the same object without affecting the other fields.
Eg:
If I want to add one more player object under players object
array
If I want to add One more group say 'Z Group' under group object array
How can I Achieve this without affecting other fields.
{
"doctype": "config:sample",
"group": [{
"name": "X Group",
"id": 1,
"players": [{
"name": "Roger Federer",
"number": 3286,
"keyword": "tennies"
},
{
"name": "P. V. Sindhu",
"number": 4723,
"keyword": "badminton"
}
]
},
{
"name": "Y Group",
"id": "2",
"players": [{
"name": "Jimmy Connors",
"number": 5623,
"keyword": "tennies"
},
{
"name": "Sachin",
"number": 8756,
"keyword": "Cricket"
}
]
}
]
}
N1QL has a huge variety of functions to operate on arrays:
https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/arrayfun.html
In your case, you could simply use ARRAY_INSERT or ARRAY_PREPEND
Check out update/update-for syntax (last example) https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/update.html
UPDATE default AS d
SET d.group = ARRAY_APPEND(d.group, {......})
WHERE .....;
UPDATE default AS d
SET g.players = ARRAY_APPEND(g.players, {......}) FOR g IN d.group WHEN g.id = 2 END
WHERE .....;
If you know which document IDs you want to update you can use the key-value subdocument API, which will generally be faster than going via N1QL for a single document update.
This will add a new player to the end of X Group's "players" array:
bucket.mutateIn(docId)
.arrayAppend("group[0].players",
JsonObject.create()
.put("name", "John Smith"))
// ... other player JSON
.execute();
And this will add a new Group Z to the "group" array:
bucket.mutateIn(docId)
.arrayAppend("group",
JsonObject.create()
.put("name", "Z Group"))
// ... other group JSON
.execute();
First, sorry for my poor english, but let me try to explain my problem.
I'm working in an application using elasticsearch java api for managed my documents.
Everything works fine, i'm able to search in DB and save on my index, i can count my documents aggregate by field and a lot of cool things, but i stucked on a weird problem.
When i trying to search my document by field called name, some documents doesn't return on search.
Let me give an example:
My documents is look like this(just for example):
id: 1
name: book
type: pdf
id: 2
name: Test of my search service
type: zip
When i trying to search, if i search by name, send as parameter the value "book", it works fine, but when i trying to search, send my parameter value "service", the result is empty.
Here my search code:
SearchRequestBuilder src1 = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery(parameter).field("name"));
Anyone knows, why this search doesn't find my parameter value "service" on name field of document with id 2?
Thanks!
Additional information:
My general index information:
{
"template": "*",
"settings": {
"index.refresh_interval": "5s"
},
"mappings": {
"_default_": {
"_all": {
"enabled": true
},
"dynamic_templates": [
{
"string_fields": {
"match": "*",
"match_mapping_type": "string",
"mapping": {
"index": "not_analyzed",
"omit_norms": true,
"type": "string"
}
}
}
],
"properties": {
"#version": {
"type": "string",
"index": "not_analyzed"
}
}
}
}
}
}
}
Well, after searching for hours and hours, i solved my problem.
To solve this issue, i used the wildcards query from elasticsearch java api and now i'm able to search a string parameter in my fields.
Here's the code:
SearchRequestBuilder srch1 = client.prepareSearch()
.setIndices("index_name")
.setTypes("type_name")
.setSearchType(SearchType.DFS_QUERY_AND_FETCH)
.setQuery(QueryBuilders.wildcardQuery("field_name", "*"+string_parameter+"*"));
After construction of your SearchRequestBuilder just add it into your MultipleSearchResponse or SearchResponse:
MultiSearchResponse sr = client.prepareMultiSearch()
.add(srch1)
.add(srch2)
.add(srch3)
.execute().actionGet();
In my case, i have 3 distinct queries, so i used MultipleSearchResponse.
I have the below json file
{
"data": [
{
"id": "254094394708288_946242468826807",
"from": {
"name": "Emirates NBD \u0628\u0646\u0643 \u0627\u0644\u0625\u0645\u0627\u0631\u0627\u062a \u062f\u0628\u064a \u0627\u0644\u0648\u0637\u0646\u064a",
"category": "Bank/Financial Institution",
"id": "254094394708288"
}
},
{
"id": "254094394708288_945515772232810",
"from": {
"name": "Emirates NBD \u0628\u0646\u0643 \u0627\u0644\u0625\u0645\u0627\u0631\u0627\u062a \u062f\u0628\u064a \u0627\u0644\u0648\u0637\u0646\u064a",
"category": "Bank/Financial Institution",
"id": "254094394708288"
}
}
]
}
I want to create a hive table based on JSON objects inside "data" JSON array. I want to do this in Java. I dont want to do "select data.id,data.from from temptable". I want to do something similar to to a select * query. It should automatically infer schema from json objects. I came to find explode function in python and scala.
http://stackoverflow.com/questions/31859271/sparksql-and-explode-on-dataframe-in-java
Is there something similar in Java??
In Java there is exactly the same thing:
org.apache.spark.sql.functions.explode(Column e)
which returns Column
You could check my answer here for the details