How to get a String inside an Object Array using MongoDB Java? - java

I'm trying to learn MongoDB and I want to get a String inside an Object Array, my MongoDB document is here:
{
"_id" : ObjectId("5f1507fed91e81246c409a59"),
"identification" : "punishment",
"lastID" : 2,
"punishmentsTypes" : [
{
"category" : "OFENSA_JOGADOR",
"reason" : "Ofensa a Jogador",
"group" : [
"HELPER",
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Ofender algum jogador",
"cases" : [
{
"1" : {
"type" : "MUTE",
"duration" : 604800000
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "FALSIFICACAO",
"reason" : "Falsificação de provas",
"group" : [
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Falsicar provas ao denunciar um jogador em nosso fórum",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 0
}
}
]
},
{
"category" : "HACK",
"reason" : "Hack",
"group" : [
"MODERATOR",
"ADMINISTRATOR",
"MANAGER",
"MASTER"
],
"description" : "Uso de cheats ou programas ilícitos",
"cases" : [
{
"1" : {
"type" : "BAN",
"duration" : 7776000000.0
}
},
{
"2" : {
"type" : "BAN",
"duration" : 0
}
}
]
}
],
"unpunishmentTypes" : [
{}
]
}
I've tried this:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
BasicDBObject query = new BasicDBObject();
BasicDBObject field = new BasicDBObject();
query.put("id", "punish");
field.put("punishmentsTypes", 1);
field.put("_id", 0);
Document test = collection.find(query).projection(field).first();
assert test != null;
Object object = test.get("punishmentsTypes");
System.out.println(object);
And that's the output:
[Document{{category=OFENSA_JOGADOR}},
Document{{category=FALSIFICACAO}}, Document{{category=HACK}}]
How can I get only the category string, to the output be: OFENSA_JOGADOR, FALSIFICACAO, HACK?

I'm not sure how did you get that result with your query but here is how I get your result:
MongoCollection<Document> collection = mongoDatabase.getCollection("settings");
Document query = new Document();
query.put("identification", "punishment");
Document test = collection.find(query).first();
List<Document> punishmentsTypes = test.getList("punishmentsTypes", Document.class);
for (Document document : punishmentsTypes) {
String category = document.getString("category");
System.out.println(category);
}

Related

I am working with Java and Springboot. Is it possible to retrieve only nested json field from a Json document in mongo

{
"_id" : ObjectId("dde3431134247d401b1cef"),
"_resourceId" : "fwf4-fefre4-ffdfwsc",
"organizationId" : 343203,
"domains" : [
{
"_resourceId" : "da7-cwcwe-2432d",
"name" : "d12.net",
"tenantId" : "A1650",
"application" : "TEST",
"activeInd" : true,
"subdomains" : [
{
"_resourceId" : "fw243-weded3-2eddas",
"name" : "name1",
"clientName" : "Andrew",
"phoneNumber" : "8573458456",
"email" : "modalwindow#gmail.com",
},
{
"_resourceId" : "bce3-cwdd32ede-23ede",
"name" : "name2",
"clientName" : "client2",
"phoneNumber" : "9999999999",
"email" : "test#gmail.com",
}
]
}
]
}
I am using Springboot and MongoTemplate for the find Query. If I want to retrieve a subdomain based on "domains.subdomain.name" field, can I get only the subdomain json from a mongo query, or do I get the entire document and then iterate and filter the subdomain in my java code.
Use $unwind and then $replaceWith
db.collection.aggregate([
{
$match: {
"domains.subdomains.name": "name1"
}
},
{
$unwind: "$domains"
},
{
$unwind: "$domains.subdomains"
},
{
$match: {
"domains.subdomains.name": "name1"
}
},
{
$replaceWith: "$domains.subdomains"
}
])
mongoplayground

Need to update only particular element in an array of mongo in java

I want to update a particular element in an array of mongo with filters.
I have already tried having using BasicDBObject, but than not able to use filter as i have collection of type MongoCollection.
MongoCollection collection = db.getCollection(tnId);
Even tried:
FindIterable<Document> document = collection.find(new BasicDBObject("DocumentName", documentName) .append("Attributes.name", "Party 1" ).append("Attributes.value", 12) .append("Attributes.actualValue.initialValue", USA));
But in this case What I get is the whole record and than I have to iterate through each Attribute again.
mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase(companyName);
MongoCollection collection = db.getCollection(tnId);
Actual data which I am passing is
{
"DocumentName" : "doc1",
"Attributes" : [
{
"name" : "Party 1",
"value" : 12,
"actualValue" : {
"initialValue" : "USA"
}
},
{
"name" : "Party 1",
"value" : 16,
"actualValue" : {
"initialValue" : "SYSTEM"
}
}
]
}
and I want to search attribute where actualValue is "USA" and Value of attribute is 12 and updated data should look like
{
"DocumentName" : "doc1",
"Attributes" : [
{
"name" : "Party 1",
"value" : 12,
"actualValue" : {
"initialValue" : "USA"
},
"updatedvalue" : {
"initialValue" : "USA",
"changedValue" : "Europe"
}
},
{
"name" : "Party 1",
"value" : 16,
"actualValue" : {
"initialValue" : "SYSTEM"
}
}
]
}
db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue.initialValue": "USA", "Attributes.$.updatedvalue.changedValue": "Europe" } })
db.collection.findOneAndUpdate({ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue.initialValue": "India", "Attributes.$.updatedvalue.changedValue": "India" } })
Try with this one
db.collection.updateMany(
{ "Attributes.actualValue.initialValue": "USA" },
{ $set: { "Attributes.$.updatedvalue" : {
"initialValue" : "USA",
"changedValue" : "Europe"
} } }
)
How I did is. I made a document where i added teh required data which i want to update it with.Say
Document valueDocument = new Document();
valueDocument.put("InitialValue", USA);
BasicDBObject query = new BasicDBObject();
query.put("Attributes", att);
BasicDBObject data = new BasicDBObject();
data.put("Attributes.$.updatedvalue" + qCLevel, valueDocument);
BasicDBObject command = new BasicDBObject();
command.put("$set", data);
collection.updateOne(query, command);
It goes and insert the data in the right place.

How to read nested array from MonogDB using Java

I need to find the record/count where eventDetails.eventDelivery.stateCode = "Y-FINISH". It could be in any element in the array list.
Just want to find where stateCode = "Y-FINISH" present in the array list.
Sample Data #1:
{
"_id" : ObjectId("5a2fb09736cf07f6a1146691"),
"activityID" : "",
"eventDetails" : [
{
"eventDelivery" : {
"digital" : {
"secureid" : "1231321212"
},
"stateCode" : "X-FINISH",
"state" : "SUCCESS"
},
{
"eventDelivery" : {
"digital" : {
"secureid" : "8762871121"
},
"stateCode" : "Y-FINISH",
"state" : "SUCCESS"
}
],
}
Sample Data #2:
{
"_id" : ObjectId("5a2fb09736cf07f6a1146691"),
"activityID" : "",
"eventDetails" : [
{
"eventDelivery" : {
"digital" : {
"secureid" : "1231321212"
},
"stateCode" : "X-FINISH",
"state" : "SUCCESS"
},
{
"eventDelivery" : {
"digital" : {
"secureid" : "8762871121"
},
"stateCode" : "Y-FINISH",
"state" : "SUCCESS"
},
{
"eventDelivery" : {
"digital" : {
"secureid" : "7651327152
},
"stateCode" : "Z-FINISH",
"state" : "SUCCESS"
}
],
}
Need to read this using Java.
Using a 3.x version of the Mongo Java driver ...
MongoClient mongoClient = ...;
MongoCollection<Document> collection = mongoClient.getDatabase("...")
.getCollection("...");
Bson filter = Filters.eq("eventDetails.stateCode", "Y-FINISH");
long count = collection.count(filter);

Translate MongoDB Query to Java

I need to use this request in java using mongodb driver
db.product.update({"orders._id":ObjectId("59328d583c5179156cb9c241")},
{
$set:{
"orders.$.description":"ccc"
}
})
my object
{
"_id" : ObjectId("59328d543c5179156cb9c240"),
"fullName" : "aaa",
"orders" : [
{
"_id" : ObjectId("59328d583c5179156cb9c241"),
"description" : "bbb"
}
]
}
Result
{
"_id" : ObjectId("59328d543c5179156cb9c240"),
"fullName" : "aaa",
"orders" : [
{
"_id" : ObjectId("59328d583c5179156cb9c241"),
"description" : "ccc"
}
] }
what i have tried
BasicDBObject set = new BasicDBObject("$set", new BasicDBObject("orders._id", myId));
set.append("$set", new BasicDBObject("description", "ccc");
product.update(searchQueryByOrderId, set);
driver used :
https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver

How to use MongoDB $let with Spring-Data?

I have a MongoDB collection of places. A typical place has most of the following fields:
{
"_id" : ObjectId("575014dc6b028f07bef53681"),
"_class" : "domain.model.PlaceV1",
"name" : "Γιασεμί",
"primary_photo_url" : "https://irs0.4sqi.net/img/general/original/34666238_STHSh6CHiC7hpAuB4rztRVg6cFc5ylfi15aRaR7zUuQ.jpg",
"seenDetails" : NumberLong(0),
"foursquare_checkins" : 646,
"foursquare_tips" : 28,
"keywords" : [
""
],
"verified" : 1,
"location" : {
"loc" : {
"type" : "Point",
"coordinates" : [
25.898318,
36.831486
]
},
"formattedAddress" : "Χώρα",
"locality" : "Amorgos",
"first_neighbourhood" : "Katapola",
"greek_locality" : "Αμοργός",
"greek_first_neighbourhood" : "Κατάπολα"
},
"contact" : {
"phone_numbers" : [
"+30 2285 074017"
]
},
"price" : {
"priceVotes" : NumberLong(0),
"price" : 0,
"priceVotesSum" : NumberLong(0)
},
"rating" : {
"rating" : 8,
"ratingVotes" : NumberLong(0),
"ratingVotesSum" : NumberLong(0)
},
"categories" : [
{
"cat_id" : NumberLong(10310061000),
"category" : "Café",
"greek_category" : "Καφετέρια",
"weight" : 4
},
{
"cat_id" : NumberLong(11610021000),
"category" : "Bar",
"greek_category" : "Μπαρ",
"weight" : 4
}
]
}
I want to make queries where the sorting will be based on a score that is a result of some expressions and conditions. From the mongo shell I have tried this:
db.place.aggregate([
{$match:{"location.locality":"Athens"}},
{$project:
{name:1, location:1, score:{
$let: {
vars:{ foursquare: {
$cond: { if: { $gte: [ "$foursquare_checkins", 500 ] }, then: 500, else: "$foursquare_checkins" }
},
rating: {$multiply:["$rating.rating", 100]},
},
in:{$add:["$$foursquare", "$$rating", "$seenDetails"]}
}
}
}
},
{$sort: {score: -1}}]).pretty();
This is a simple example of my queries. The score will contain more complex expressions like the distance from a location. The problem is that I cannot find a way to use the $let and the $cond operator in my Java code with Spring. Could anybody help?
You should be able to do this using nested DBObject and a Custom Aggregation Operation.
For Example:
Map operations = new HashMap();
operations.put("name", 1);
operations.put("location", 1);
operations.put("score", new BasicDBObject("$let", new BasicDBObject("vars", new BasicDBObject())));
Then you can create a CustomAggregationOperation to add this to your project
CustomAggregationOperation project = new CustomAggregationOperation(new BasicDBObject("$project", operation));
This will give you the following pipeline:
{ "$project" : { "score" : { "$let" : { "vars" : { }}} , "name" : 1 , "location" : 1}}
Then you can add your other stages:
Aggregation aggregate = Aggregation.newAggregation(match, project, sort);
public class CustomAggregationOperation implements AggregationOperation {
private DBObject operation;
public CustomAggregationOperation (DBObject operation) {
this.operation = operation;
}
#Override
public DBObject toDBObject(AggregationOperationContext context) {
return context.getMappedObject(operation);
}
}

Categories

Resources