mongodb query to find value in json - java

I started working with MongoDB. I prepared some basic training JSON:
{
"header": {
"Hotel": {
"data": [
{
"name": "Hilton",
"Id": "1231213421"
}
]
},
"standard": "5",
"priceStage": "4"
},
"data": {
"http": {
"strean": {}
}
}
}
and I wrote a query like this:
db.hotel.find( "data": { Id: "1231213421"})
Why query does not return anything?

You're trying to match on an element within an array and you don't need to match on the entire array. So,something like the following will work:
db.hotel.find({"header.Hotel.data": {"$elemMatch": {"Id": "1231213421"}}} );

Related

How to get property value direct from mongodb in JAVA

Hi everyone I have a collection of documents like bellow. I want to directly get "rights" from roles array for params: _id, groups._id, roles._id using java mongo driver.
{
"_id": 1000002,
"groups": [
{
"_id": 1,
"roles": [
{
"rights": 3,
"_id": 1
},
{
"rights": 7,
"_id": 2
},
{
"rights": 3,
"_id": 3
}
]
}
],
"timestamp": {
"$date": {
"$numberLong": "1675267318028"
}
},
"users": [
{
"accessProviderId": 1,
"rights": 1,
"_id": 4
},
{
"accessProviderId": 1,
"rights": 3,
"_id": 5
}
]
}
I have AccessListItem class which represents this document and I have used Bson filters to get it from mongo, but after fetching i had to get information through java function.. I want to get int value directly from mongo base.
Bson fileFilter = Filters.eq("_id", itemId);
Bson groupFilter = Filters.elemMatch("groups", Document.parse("{_id:"+groupId+"}"));
Bson roleFilter = Filters.elemMatch("groups.roles", Document.parse("{_id:"+role+"}"));
Bson finalFilter = Filters.and(fileFilter, Filters.and(groupFilter,roleFilter));
MongoCollection<AccessListItem> accessListItemMongoCollection = MongoUtils.getAccessCollection(type);
AccessListItem accessListItem = accessListItemMongoCollection.find(finalFilter).first();
The short answer is you can't.
MongoDB is designed for returning documents, that is, objects containing key-value pairs. There is no mechanism for a MongoDB query to return just a value, i.e. it will never return just 3 or [3].
You could use aggregation with a $project stage at the end to give you a simplified object like:
{ rights: 3}
In javascript that might look like:
db.collection.aggregate([
{$match: {
_id: itemId,
"groups._id": groupId,
"groups.roles._id": role
}},
{$project: {
_id: 0,
group: {
$first: {
$filter: {
input: "$groups",
cond: {$eq: ["$$this._id",groupId]}
}
}
}
}},
{$project: {
"roles": {
$first: {
$filter: {
input: "$group.roles",
cond: { $eq: [ "$$this._id",role]}
}
}
}
}},
{$project: {
rights: "$roles.rights"
}}
])
Example: Playground
I'm not familiar with spring boot, so I'm not sure what that would look like in Java.

Spring Data with mongodb query to bring some elements from the array

I'm trying to bring several items from an array into an object, but the result is just one item from that array. What I want is to bring several items from this array.
I have:
{
"title": "market",
"products": [
{"name": "pepperoni pizza"},
{"name": "mozzarella pizza"},
{"name": "yogurt"},
{"name": "soda"},
]
}
And:
Query query = new Query();
query.fields().elemMatch("products", Criteria.where("name").regex("pizza", "i"))
.include("products")
.include("title");
mongoTemplate.find(query, Business.class);
Outcome:
{
"title": "market",
"products": [
{"name": "pepperoni pizza"}
]
}
But I want:
{
"title": "market",
"products": [
{"name": "pepperoni pizza"},
{"name": "mozzarella pizza"}
]
}
can't help with spring data version but this is the mongo query it should be generating:
db.collection.aggregate([
{
$match: {
'products.name': /pizza/i
}
},
{
$set: {
products: {
$filter: {
input: "$products",
cond: { $regexMatch: { input: "$$this.name", regex: /pizza/i } }
}
}
}
}
])

how to create linked hash map object for this json

I am trying to call an API using Retrofit in android. For this API I need the input parameter JSON object in proper sequence.
Only if I have the json in required sequence I get successful response from the API, otherwise it gives an error. To handle this issue I got one solution that is to first create a LinkedHashMap of input parameter then create the JSON of that LinkedHashMap. This way I'm acheaving the response from api.
but right now im confused how to create linkedHash map for below json
{
"RequestXml": {
"Authenticate": {
"InterfaceCode": "1",
"InterfaceAuthKey": "AirticketOnlineWebSite",
"AgentCode": "MOS0000001",
"Password": "KGBW5P"
},
"BookTicketRequest": {
"TrackNo": "0$182967|4|1AO",
"MobileNo": "9099776464",
"AltMobileNo": "9898989898",
"Email": "abc#gmail.com",
"Address": "Test",
"ClientRequestID": "",
"Passengers": {
"Passenger": [
{
"PaxSeqNo": "1",
"Title": "Mr",
"FirstName": "Savan",
"LastName": "Test",
"PassengerType": "A",
"DateOfBirth": "01/12/1992",
"PassportNo": "RTTTTGGBGB56356",
"PassportExpDate": "01/12/2024",
"PassportIssuingCountry": "IND",
"NationalityCountry": "IND"
}
]
},
"Segments": {
"Segment": [
{
"TrackNo":"0$182967|4|1AO",
"SegmentSeqNo": "1",
"AirlineCode": "UK",
"FlightNo": "888",
"FromAirportCode": "BOM",
"ToAirportCode": "DEL",
"DepDate": "30/09/2019",
"DepTime": "14:00",
"ArrDate": "30/09/2019",
"ArrTime": "16:00",
"FlightClass": "E",
"MainClass": "Y"
}
]
},
"AdditionalServices": {
},
"TotalAmount": "4735",
"MerchantCode": "PAY9zJhspxq7m",
"MerchantKey": "eSpbcYMkPoZYFPcE8FnZ",
"SaltKey": "WHJIIcNjVXaZj03TnDme",
"IsTicketing": "Yes"
}
}
}

how to calculate total value for the below JSON value U.O.M Wise in Java

how to calculate total value for the below JSON value U.O.M Wise in Java?
sequence can be vary. We cannot expect number of uoms and sequence of results.
i have created hashset and made unique uom.
{
value=100
uom=kg
},
{
value=200
uom=kg
},
{
value=100
uom=lt
},
{
value=100
uom=ab
},
{
value=100
uom=lt
}
Please provide some code ref
This is not valid JSON as it uses = as key\value separator (change to something like this and use tools like JSONLint to validate):
[{
"value": "100",
"uom": "kg"
}, {
"value": "200",
"uom": "kg"
}, {
"value": "100",
"uom": "lt"
}, {
"value": "100",
"uom": "ab"
}, {
"value": "100",
"uom": "lt"
}
]
Even having this structure you can parse it into a collection of touples (value, uom) and then just sum everything having same uom
For example you can use this:
javax.json.JsonArray body = Json.createReader(new StringReader(YOUR_JSON_STRING)).readArray();
and read a JSON to array of touples

Iterate last values present in a JSON response using java

I need to iterate and get the last values like name, url and color from below JSON response. Using java/gson api. Please help me on this.
{
"Title": {
"desc": [
{
"name": "PRE_DB",
"url": "http://jenkins.example.com/job/my_first_job/",
"color": "blue_anime"
},
{
"name": "SDD_Seller_Dashboard",
"url": "http://jenkins.example.com/job/my_second_job/",
"color": "blue_anime"
}
]
}
}
example output :
name : SDD_Seller_Dashboard
color :blue_anime
JSONObject data = new JSONObject(your_JSON_Repsonse);
JSONArray data_desc=data.getJSONArray(desc);
for(int i=0;i<=data_desc.length();i++)
{
name=data_desc.getString("name");
url=data_desc.getString("url");
color=data_desc.getString("color");
}

Categories

Resources