How to update Mongo DB document with complex structure - java

I have a mongoDB document with the following structure
{
"id": 9595511812,
"Feeds": [
{
"department": "mseb",
"consumer_number": 1234567890,
"due_date": "2016-11-11",
"due_amount": 400,
"balance_amount": 0,
"unitsConsumed": 40,
"freezeDate": "2016-11-11",
"lastPaidDate": "2016-11-11",
"billNumber": "9877",
"id": "1",
"paid": false
},
{
"department": "mseb",
"consumer_number": 1234567890,
"due_date": "2016-11-21",
"due_amount": 400,
"balance_amount": 0,
"unitsConsumed": 40,
"freezeDate": "2016-11-21",
"lastPaidDate": "2016-11-21",
"billNumber": "9877",
**"id": "2",**
"paid": false
}
]
}
I want to update paid == true for Feed with id=2 (** marked field above). How can I do that in using mongo java client?
I have tried
DB db = DBConnection.getDatabaseConnection();
DBCollection table = db.getCollection("customer");
BasicDBObject newDocument = new BasicDBObject();
newDocument.append("$set", new BasicDBObject().append("Feeds.paid", "true"));
BasicDBObject searchQuery = new BasicDBObject().append("id", "9595511812");
table.update(searchQuery, newDocument);

Feeds is an array, and you're updating the 2nd element, so the set would end with:
.append("Feeds.1.paid", "true"));
instead of:
.append("Feeds.paid", "true"));

Related

How to update nested elasticsearch value via bulkrequest?

We are using AWS Elasticsearch - 7.7 Version
I already followed Update nested field in an index of ElasticSearch with Java API
I have below JSON Elastic Search
{
"_index": "product",
"_type": "_doc",
"_source": {
"id": 1,
"name": "test",
"properties": [{
"id": 1,
"qty": 10
}]
}
}
I have below code
BulkRequest request = new BulkRequest();
request.add(new UpdateRequest(<ES Endpoint>, 1))
.doc(XContentType.JSON, "name", "TEST 1"));
BulkResponse bulkResponse = restClient.bulk(request, RequestOptions.DEFAULT);
How should I update "properties" value "qty"?
https://www.elastic.co/guide/en/elasticsearch/client/java-api/6.8/java-docs-update.html
You can pass a Map with all fields to update in the doc() call:
Map doc = new HashMap();
doc.put("name", "TEST 1");
doc.put("qty", 12);
request.add(new UpdateRequest("index", 1)
.doc(XContentType.JSON, doc));

I need to rename one field in document

Here is the code :
AggregateIterable<Document> result = chatLogCollection.aggregate(Arrays.asList(
new Document("$match", new Document("displayName", "user")),
new Document("$group", new Document("_id","$sessionGUID")
.append("time", new Document("$first","$ts"))
.append("makerID", new Document("$first","$makerID"))),
new Document("$sort", new Document("time", -1)),
new Document("$skip", skip),
new Document("$limit", limit)
));
This will generate the below type out put.
{
"displayName": "test test",
"_id": "123a54be-4b69-cd49-edb3-9b264fea077b",
"time": {
"$date": 1499759619016
},
"makerID": "xxxxx"
}
I need to format this to look like this:
{
"displayName": "test test",
"sessionID": "123a54be-4b69-cd49-edb3-9b264fea077b",
"time": {
"$date": 1499759619016
},
"makerID": "xxxxx"
}
That means i need to appear _id as sessionId. Please help me to do that.I am using mongoDB, java and windows 7.

Add field to subdocument from document returned from query

I want to add a field to the returned subdocument like this:
{
"type": "product",
"code": "abc",
"team": "A1",
"modules": [{
"type": "module",
"code": "cde"
//Add a new field here
}]
}
I can add new field in document by Document.append() but can't add to the subdocument.
Here is my Java code:
BasicDBObject query = new BasicDBObject("code", "abc");
AggregateIterable<Document> findIterable = collection.aggregate(Arrays.asList(
new Document("$match", query),
new Document("$project", new Document("_id", 0).append("type", 1)
.append("code", 1)
.append("team", 1)
.append("modules", 1)
),
new Document("$sort", new Document("code", 1))
));
mongoCursor = findIterable.iterator();
while(mongoCursor.hasNext()){
Document document = mongoCursor.next();
}
Can someone give some help please? Thanks a lot in advance!!!

Get last inserted document with tag MongoDB Java

I am working in Java using the 2.6 Java driver.
I am using the "i" tag to identify the site.
What is the best way to query in order to get the last inserted document with "i" = "99159" ?
Please provide some example code.
An example document in mongo:
{
"_id": ObjectId("560bc0eee4b01a37814ee444"),
"dataDate": "2015-09-30T11:00:00Z",
"i": "99159",
"lat": "50.61359",
"lon": "-1.95875",
"name": "SWANAGE",
"country": "ENGLAND",
"continent": "EUROPE",
"elevation": "10.0",
"Period": {
"type": "Day",
"value": "2015-09-30Z",
"Rep": {
"H": "75.9",
"T": "14.7",
"Dp": "10.5",
"MinSinceMidnight": "600"
}
}
}
As you have _id as ObjectId, so you can sort your data on _id to get last inserted record.
Sample code:
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
MongoClient mongo = new MongoClient("localhost", 27017);
DB mongodb = (DB) mongo.getDB("testDB");
DBCollection collection = mongodb.getCollection("collection");
BasicDBObject findObject = new BasicDBObject().append("i","99159");
BasicDBObject sortObject = new BasicDBObject().append("_id", -1);
DBCursor cur = collection.find(findObject).sort(sortObject).limit(1);
DBObject obj = cur.one();

Java mongodb - find then average

Okey, let's start. Imagine that we have the next mongo collection:
{
"city": "TWENTYNINE PALMS",
"loc": [-116.06041, 34.237969],
"pop": 11412,
"state": "CA",
"_id": "92278"
}
{
"city": "NEW CUYAMA",
"loc": [-74.823806, 34.996709],
"pop": 80,
"state": "CA",
"_id": "93254"
}
{
"city": "WATERBURY",
"loc": [-72.996268, 41.550328],
"pop": 25128,
"state": "CT",
"_id": "06705"
}
Notice that loc array is [latitude,longitude]
I would like to obtain using java mongo driver the "pop" average of the cities that have the altitude beetwen -75,-70.
So, using SQL I know that the query is:
SELECT avg(pop)
WHERE loc.altitude > -75 AND lloc.altitude < -70
I am very noob in mongodb, this is my current code:
BasicDBObject doc = new BasicDBObject("loc.0", new BasicDBObject("$gte",
-75).append("$lte", -70));
DBCursor cursor = collection.find(doc);
The previous code returns me all the documents that altitude are beetwen (-75,-70), but I do not know how to obtain the average,using mongo driver, I know that I can iterate over results using java..
Thank you
Use the aggregation framework with following aggregation pipeline (Mongo shell implementation):
db.collection.aggregate([
{
"$match": {
"loc.0": { "$gte": -75 },
"loc.1": { "$lte": 70 }
}
},
{
"$group": {
"_id": 0,
"average": {
"$avg": "$pop"
}
}
}
])
With the example above, this outputs to console:
/* 1 */
{
"result" : [
{
"_id" : 0,
"average" : 12604
}
],
"ok" : 1
}
With Java, this can be implemented as follows:
DBObject match = new BasicDBObject();
match.put("loc.0", new BasicDBObject("$gte", -75));
match.put("loc.1", new BasicDBObject("$lte", 70));
DBObject groupFields = new BasicDBObject( "_id", 0);
groupFields.put("average", new BasicDBObject( "$avg", "$pop"));
DBObject group = new BasicDBObject("$group", groupFields);
AggregationOutput output = collection.aggregate( match, group );

Categories