Group by age groups in mongo db - php

I am using following mongo db query . and it is showing me only age groups of my personas data.
db.amplifyindex.aggregate([
{ $unwind: "$demographic" },
{ $match : { 'demographic.is_latest':"active",
'demographic.date_of_birth' : { $exists : true} } },
{ $project : {"ageInMillis" : {$subtract : [new Date(),
"$demographic.date_of_birth"] } } },
{ $project : {"age" : {$divide : ["$ageInMillis", 31558464000] }}},
{ $project : {"age" : {$subtract : ["$age", {$mod : ["$age",1]}]}}},
])
The result object by this query is:
{
"_id" : ObjectId("58a42cbbdb5d880c1e000029"),
"age" : 29.0
}
I want to get data in a way as :
{
"_id" : ObjectId("58a42cbbdb5d880c1e000029"),
"age" : 10-30
"personas" : 10
}
Complete data structure in my scenario is given as :
{
"_id" : ObjectId("58a42cbbdb5d880c1e000029"),
"persona_email" : "milton.ullrich#gmail.com",
"company_id" : "1",
"date_added" : ISODate("2017-02-15T10:23:15.000Z"),
"demographic" : [
{
"persona_fname" : "Hayden",
"middle_name" : "Jacobs",
"persona_lname" : "Schmeler",
"gender" : "male",
"date_of_birth" : ISODate("1987-06-16T19:00:00.000Z"),
"marital_status" : "single",
"height" : "2.1 feet",
"weight" : "5 kg",
"measurement" : {
"waist" : "34 inch"
},
"disabilities" : "No",
"race" : "Asian",
"nationality" : "Jordan",
"life_cycle" : "empty nest",
"children" : {
"gender" : "female",
"date_of_birth" : ISODate("1987-06-16T19:00:00.000Z")
},
"medicare_no" : "4916725587565",
"driving_licence_no" : "PACBALM420M",
"id_no" : "4485872783336",
"passport_no" : "OCRFHCNR",
"residential_address" : {
"unit_no" : 603,
"street_no" : "34863 Ondricka Viaduct Apt. 154",
"street_name" : "84799 Little Wall",
"suburb" : "West Virginia",
"postal_code" : "23873",
"state" : "Dominica",
"country" : "Cook Islands"
},
"work_address" : {
"unit_no" : "6011865161287875",
"street_no" : "630 Beer Underpass Suite 372",
"street_name" : "87672 Lind Burg",
"suburb" : "West Virginia",
"postal_code" : "84356-3662",
"state" : "Qatar",
"country" : "British Indian Ocean Territory (Chagos Archipelago)"
},
"shipping_address" : {
"unit_no" : "6011865161287875",
"street_no" : "8292 Langosh Drive Suite 065",
"street_name" : "9844 Nicolas Mount",
"suburb" : "West Virginia",
"postal_code" : "07014",
"state" : "Togo",
"country" : "Tunisia"
},
"job_title" : "Geoscientists",
"employer_name" : "Aufderhar Group",
"income" : 72577,
"phone_numbers" : {
"work_phone" : "993-783-7499",
"home_phone" : "701.546.7016",
"mobile" : "1-346-729-4392"
},
"emails" : {
"work_emails" : "nikolaus.asa#gmail.com",
"personal_emails" : "emmitt68#gmail.com"
},
"languages" : "italian",
"data_source" : "soldi",
"date_added" : ISODate("2017-02-15T10:23:15.000Z"),
"source" : "soldi",
"is_latest" : "inactive"
},
{
"persona_fname" : "Julien",
"middle_name" : "Hirthe",
"persona_lname" : "Schaefer",
"gender" : "female",
"date_of_birth" : ISODate("1987-06-16T19:00:00.000Z"),
"marital_status" : "single",
"height" : "2.1 feet",
"weight" : "5 kg",
"measurement" : {
"waist" : "34 inch"
},
"disabilities" : "No",
"race" : "Asian",
"nationality" : "Sudan",
"life_cycle" : "single",
"children" : {
"gender" : "female",
"date_of_birth" : ISODate("1987-06-16T19:00:00.000Z")
},
"medicare_no" : "4024007131689860",
"driving_licence_no" : "OGOSUOIFSDN",
"id_no" : "5523297913341227",
"passport_no" : "WWZYTE489ZR",
"residential_address" : {
"unit_no" : 603,
"street_no" : "338 Mueller Gardens Suite 397",
"street_name" : "6302 Catalina Isle",
"suburb" : "West Virginia",
"postal_code" : "97534",
"state" : "Antarctica (the territory South of 60 deg S)",
"country" : "Turks and Caicos Islands"
},
"work_address" : {
"unit_no" : "6011865161287875",
"street_no" : "8561 Jesus Ridges Apt. 662",
"street_name" : "1869 Josiah Wall Apt. 347",
"suburb" : "West Virginia",
"postal_code" : "14810",
"state" : "Zambia",
"country" : "Mongolia"
},
"shipping_address" : {
"unit_no" : "6011865161287875",
"street_no" : "514 Heller Center",
"street_name" : "835 Paxton Cliffs Suite 040",
"suburb" : "West Virginia",
"postal_code" : "48942-3845",
"state" : "Palau",
"country" : "Belize"
},
"job_title" : "Geoscientists",
"employer_name" : "Aufderhar Group",
"income" : 72577,
"phone_numbers" : {
"work_phone" : "(553) 892-7614 x573",
"home_phone" : "796.308.3001 x88799",
"mobile" : "+1-876-339-1755"
},
"emails" : {
"work_emails" : "prohaska.katelynn#hotmail.com",
"personal_emails" : "ozulauf#jenkins.com"
},
"languages" : "german",
"data_source" : "soldi",
"date_added" : ISODate("2017-02-15T10:23:15.000Z"),
"source" : "soldi",
"is_latest" : "active"
}
]
}

Within your group pipeline, create the age ranges as part of the _id key and this can be done through the use of the $concat and "$cond" operators. Consider running the following pipeline to get the desired result:
db.amplifyindex.aggregate([
{ "$unwind": "$demographic" },
{ "$match": { "demographic.is_latest": "active" } },
{
"$project": {
"age": {
"$divide": [
{
"$subtract": [
new Date(),
{ "$ifNull": ["$demographic.date_of_birth", new Date()] }
]
},
1000 * 86400 * 365
]
}
}
},
{
"$group": {
"_id": {
"$concat": [
{ "$cond": [ { "$lte": [ "$age", 0 ] }, "Unknown", ""] },
{ "$cond": [ { "$and": [ { "$gt": ["$age", 0 ] }, { "$lt": ["$age", 10] } ]}, "Under 10", ""] },
{ "$cond": [ { "$and": [ { "$gte": ["$age", 10] }, { "$lt": ["$age", 31] } ]}, "10 - 30", ""] },
{ "$cond": [ { "$and": [ { "$gte": ["$age", 31] }, { "$lt": ["$age", 51] } ]}, "31 - 50", ""] },
{ "$cond": [ { "$and": [ { "$gte": ["$age", 51] }, { "$lt": ["$age", 71] } ]}, "51 - 70", ""] },
{ "$cond": [ { "$gte": [ "$age", 71 ] }, "Over 70", ""] }
]
},
"personas": { "$sum": 1 }
}
},
{ "$project": { "_id": 0, "age": "$_id", "personas": 1 } }
])
In the above pipeline, I've taken out the query for null date fields and replaced it with the $ifNull operator within the $project pipeline. This will return the current date where the birthday field is null and thus yields an age of 0 years which will fall into a special age range bracket, thus the need to include all the documents, including the ones where the date of birth field missing.
In the case where the $concat operator is used for all $cond expressions, the combination is crucial as it acts as a case statement where otherwise there will be nested $cond operators.
To understand this design, take the third $cond expression
{
"$cond": [
{
"$and": [
{ "$gte": ["$age", 10] },
{ "$lt": ["$age", 31] }
]
},
"10 - 30", // matching if
"" // else
]
},
which essentially expresses the logic
if ( "$age" >= 10 && "$age" < 31 ) { return "10 - 30"; }
else return "";
$concat is useful when used with the $cond operators as the expression will return an empty value except the matching one, which in turn will return the age group.
For example, an age of 30.645411 would return
"$concat": [ "", "", "10 - 30", "", "", "" ]
which then gives you an _id with value of "10 - 30".

Related

Unable to loop through json data using foreach()

I'm using an API to retrieve a json file, that I then want to echo out onto my webpage.
I am able to echo the data individually, like so :
echo $json2['result']['reviews'][0]['author_name'];
However, as soon as I try to loop through the data with a foreach loop(), i get the error:
Warning: Array to string conversion in C:\xampp\htdocs\cw\tester.php on line 36
Array
Warning: Attempt to read property "result" on array in C:\xampp\htdocs\cw\tester.php on line 38
Warning: Attempt to read property "reviews" on null in C:\xampp\htdocs\cw\tester.php on line 38
Warning: foreach() argument must be of type array|object, null given in C:\xampp\htdocs\cw\tester.php on line 38
I'm sure its simple as json isn't too complicated, but I can't get it to work, as I don't understand what my problem is.
this is the for loop I tried to create:
foreach ($json2->result->reviews as $my_data){
foreach ($my_data -> author_name as $names){
echo $names . '<br>';
}
}
and this is the json file (I want to grab data from 'reviews'):
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "Antrim Road",
"short_name" : "Antrim Rd",
"types" : [ "route" ]
},
{
"long_name" : "Belfast",
"short_name" : "Belfast",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Newtownabbey",
"short_name" : "Newtownabbey",
"types" : [ "postal_town" ]
},
{
"long_name" : "Belfast",
"short_name" : "Belfast",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Northern Ireland",
"short_name" : "Northern Ireland",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United Kingdom",
"short_name" : "GB",
"types" : [ "country", "political" ]
},
{
"long_name" : "BT36 7PN",
"short_name" : "BT36 7PN",
"types" : [ "postal_code" ]
}
],
"adr_address" : "\u003cspan class=\"street-address\"\u003eAntrim Road\u003c/span\u003e, \u003cspan class=\"extended-address\"\u003eBelfast\u003c/span\u003e, \u003cspan class=\"locality\"\u003eNewtownabbey\u003c/span\u003e \u003cspan class=\"postal-code\"\u003eBT36 7PN\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eUK\u003c/span\u003e",
"business_status" : "OPERATIONAL",
"formatted_address" : "Antrim Rd, Belfast, Newtownabbey BT36 7PN, UK",
"formatted_phone_number" : "028 9077 6277",
"geometry" : {
"location" : {
"lat" : 54.6577821,
"lng" : -5.943665699999999
},
"viewport" : {
"northeast" : {
"lat" : 54.65913108029149,
"lng" : -5.942316719708497
},
"southwest" : {
"lat" : 54.6564331197085,
"lng" : -5.945014680291502
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/generic_business-71.png",
"international_phone_number" : "+44 28 9077 6277",
"name" : "Belfast Zoo",
"photos" : [
{
"height" : 1243,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/111863060002111236588\"\u003eBelfast Zoo\u003c/a\u003e"
],
"photo_reference" : "ATtYBwLPDngDqoLqrE-KZnFdp94V6uH2rOa-x4B2A7GVXOKD7raGPWiKtjNeDKEDpXrvbl9hPrjiE82RrHy-WFTyaIM51I7lE4f_gQavJlNtEcI8QCyNlgXdNbdubkFBTwOQpYQojvtcLavYu6RIHmiAQA8DnO3IQpX7pd3OIUC2drtfN85w",
"width" : 1776
},
{
"height" : 2988,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/100936618118839321951\"\u003eAmanda Lewis\u003c/a\u003e"
],
"photo_reference" : "ATtYBwI4nDTtt9wy2B18qwRhRrAd90Z24tQL5KpKDYw8UqHLbMXeazhIQzG0B72gNJ5qASZT3lVzw9IQ8789ovoqmfvhBU9biLUSjYWDFZRUz-UBIAvc-7ma69soGhze5ysjzg9K67e14axna-npfP0A64cc2v5pHO14hph0l8uBRovb4tnL",
"width" : 5312
},
{
"height" : 2988,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/116390912159770135890\"\u003eBeti Na\u003c/a\u003e"
],
"photo_reference" : "ATtYBwIBVFK2xPo7SoaT35yaxTvJo27782EJWXiLAlB7MuA3XHAbRd_DfJ7T6ZBZLVmpeyCO7GgyF06kkPtDak58HlGEup-IAyGXoCS6byofWqzqjjwvPx_FmN5tY2XfSU4Ocvs-UYyxnCA9T0q00egfJCL92XTMLHib5TDqQeAQY3r6pMKS",
"width" : 5312
},
{
"height" : 9248,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/106644795451552578979\"\u003eMatthew mcmullan\u003c/a\u003e"
],
"photo_reference" : "ATtYBwL1S6nVnplt3cRoJgsifwFdNo6fgcgd2GLpJqNuYvCdWBCMkvXNcFMiQ07OOzptgfsiYedU0xgUzG5D_VRXVPddqwgZQa0A4uBXoX43GFAU9rh3AB0u8MKY0M_1FB56GwVBEToT7rlShjLS5_KI1hOowB4ZdptMI_twgQwkzcEmIkg0",
"width" : 6936
},
{
"height" : 2988,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/116390912159770135890\"\u003eBeti Na\u003c/a\u003e"
],
"photo_reference" : "ATtYBwKFyQSrzrvX0X4tDu26wN10cgbo5w6JIlRQTWC4ttbAboV7ICKCuLWVazvoTdpBT1UpKGTsQHyVoZhC5f-1CBYtwZQCuTrOyGy8at0zsHW9ENLjq5q_zvB9LCHdgCUWMgWnBRzlYonNYCkPzRu-qORlJSX8X66-miqdbtXUFxMz-o3H",
"width" : 5312
},
{
"height" : 3823,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/116284097622909280304\"\u003eBrian Cunningham\u003c/a\u003e"
],
"photo_reference" : "ATtYBwJwf5rfaz8OqJ4AbQMgxKU3rKUf-4O6_Z6ME6vuZ5X6zgaSKdqvN_IxHuYqZIZWtPBlTFeYs4AzcH9oXWHQjrKdX5nGXelND-OoMe_Srp5pgGwmEr2f3TVQFktQAyv3NBA5l4JcBiKlb9wR_EueGaiEI6aM6VQobg6ab8CTXTGQclB7",
"width" : 5735
},
{
"height" : 4000,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/109005734355336105418\"\u003eWilliam Young\u003c/a\u003e"
],
"photo_reference" : "ATtYBwKlMZ9zSIi-AkC5M9nyMiOo3ly_-NtKqrFpz5A-_YFXyEc-Mn9APluh__SgUHPwgbNkZ27BjUYtK2Deb5MHax6yICyIC9RzZGOD4AY_F1pSPUXwwkMwuW66JMx_ZsgW-GpkJKo9m89Cua_mFBOfwrvxSpm66lwfpuQUsUz2fibwMKEQ",
"width" : 2723
},
{
"height" : 3024,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/100719597211687837516\"\u003eJonathan Kelly\u003c/a\u003e"
],
"photo_reference" : "ATtYBwJtrdU_MSyxj8Tzh-wt4fJeI9xnMBJSYus2rCCBRhVb1z64xhreHcSB3-QLRvoVS-XYSYLMhEyvtIBdsiNowQaBBHJEAUXcWtpsyvRCYjZU8a9gr9SCJpmo_Wj42CJTxR65cKlGC7i5dEDgssPUqmRZug8B5AtjJ3tuzGUqIBKcNdjz",
"width" : 4032
},
{
"height" : 3024,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/104554106193648036788\"\u003eAjay Jose\u003c/a\u003e"
],
"photo_reference" : "ATtYBwJzspaF2TTMtjQYmDJ1_IOJmjH6apJBqz9UJ8POUX1M8airOQja9pZQmrK0SONdFQUgTV-HXFI57sGHFmhetWxMilc5jPU_JcBQT6bhyX6Wqt21tbsV1GM9ySMXbYqMYwlSMBGrP9fiK32hbkxy7A5ecjX88QCYdvVUGqf2hbB8o2bM",
"width" : 4032
},
{
"height" : 3024,
"html_attributions" : [
"\u003ca href=\"https://maps.google.com/maps/contrib/100719597211687837516\"\u003eJonathan Kelly\u003c/a\u003e"
],
"photo_reference" : "ATtYBwKqikSfsSeOGFFpSIx1g9O1iDMA3Xn_gf--hC2I9pJCOzDLFMkkLghF9Sr3j6kftlrCx8SSVhEPuZOZXxBOanl3qUh4UA5bvV7QTt3tD5Qje9Tnkd4319h-91dBZshFvd3y8rJb5WK_98bzc06DMIjCtJOPcQ3j1jV0Pr-DpGsPOH0-",
"width" : 4032
}
],
"place_id" : "ChIJ88iCe5inYUgRdeXmfCtuvu4",
"plus_code" : {
"compound_code" : "M354+4G Belfast, UK",
"global_code" : "9C6PM354+4G"
},
"rating" : 4.3,
"reference" : "ChIJ88iCe5inYUgRdeXmfCtuvu4",
"reviews" : [
{
"author_name" : "Karen Hoad",
"author_url" : "https://www.google.com/maps/contrib/103129952317107981705/reviews",
"language" : "en",
"profile_photo_url" : "https://lh6.googleusercontent.com/-OkGM8wAyHz8/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucn55YdMQZ1BX6ods-S34cieMQODrg/s128-c0x00000000-cc-rp-mo-ba5/photo.jpg",
"rating" : 4,
"relative_time_description" : "6 months ago",
"text" : "Great place just not good when raining as the animals stay in",
"time" : 1599236033
},
{
"author_name" : "John Lee Ashworth",
"author_url" : "https://www.google.com/maps/contrib/116452096322094109908/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/-_ZpK7cdK1NI/AAAAAAAAAAI/AAAAAAAAAAA/AMZuuclmcdFSQNilc5MfhJ3m8rRqzAXO_A/s128-c0x00000000-cc-rp-mo/photo.jpg",
"rating" : 3,
"relative_time_description" : "6 months ago",
"text" : "Love zoos, love animals, hate nothing but steep hills though",
"time" : 1598880406
},
{
"author_name" : "Clare",
"author_url" : "https://www.google.com/maps/contrib/116989491220973031798/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/a-/AOh14GjK9VEovk8XRG41K9vVtu0SKRIHQdXp6Gb79opr_g=s128-c0x00000000-cc-rp-mo-ba2",
"rating" : 2,
"relative_time_description" : "5 months ago",
"text" : "Very little animals to see.",
"time" : 1600628749
},
{
"author_name" : "Tammy 102",
"author_url" : "https://www.google.com/maps/contrib/111672456708879530776/reviews",
"language" : "en",
"profile_photo_url" : "https://lh5.googleusercontent.com/-ngjoEXxeE8Q/AAAAAAAAAAI/AAAAAAAAAAA/AMZuucnTOkOTeq8ecWLEVbSs7UBnsUPmSQ/s128-c0x00000000-cc-rp-mo-ba3/photo.jpg",
"rating" : 5,
"relative_time_description" : "5 months ago",
"text" : "To check prices",
"time" : 1600610117
},
{
"author_name" : "Mark Woonton",
"author_url" : "https://www.google.com/maps/contrib/106800516570033737478/reviews",
"language" : "en",
"profile_photo_url" : "https://lh3.googleusercontent.com/a-/AOh14GgnYZybrP-MTC4U45agdIlXMIFDIuH1v6roRuJAWQ=s128-c0x00000000-cc-rp-mo",
"rating" : 5,
"relative_time_description" : "6 months ago",
"text" : "Amazing zoo, so much to see, a great day out",
"time" : 1599993064
}
],
"types" : [ "zoo", "tourist_attraction", "point_of_interest", "establishment" ],
"url" : "https://maps.google.com/?cid=17203308759660029301",
"user_ratings_total" : 2714,
"utc_offset" : 0,
"vicinity" : "Antrim Road, Belfast",
"website" : "http://www.belfastzoo.co.uk/"
},
"status" : "OK"
}

How to parse multi associative arrays to echo out by key values

Hey guys Im a student and my question might seem simple but i can't find the right answer anywhere. Please take a look. as you can see $parsed_json works fine with this code $parsed_json = $parsed_json['photos']; how do i add another key of the array there? i tried $parsed_json = $parsed_json[(['photos']['contactInfo'])]; but did now work. Any help will much appreciated. Thank you.
<?php
$json_string = file_get_contents("api/goes/here")
$parsed_json = json_decode($json_string, true);
print_r($parsed_json);
$parsed_json = $parsed_json[(['photos']['contactInfo'])];
foreach($parsed_json as $key => $value)
{
echo $value['typeName'] . '<br>';
echo $value['typeId'] . '<br>';
echo $value['familyName'] . '<br>';
// etc
?>
-------------JSON CONTENT------------------------------
{
"status" : 200,
"requestId" : "0ef05ee4-6bab-4488-a80c-04ce050ca074",
"likelihood" : 0.95,
"photos" : [ {
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/651f183b3a1bd463ef5298a2877f2c4f_0c027087db5cd03d244a7dd42e42fc969fa8d636bffd7635b46172c8a597aa73",
"isPrimary" : true
}, {
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://d2ojpxxtu63wzl.cloudfront.net/static/d0080f4ccd9ea21340b0fd994f82c0e0_2acdc7de41111f7d58e7544ed970b78e72f1739784417c146d5689d96ce79137"
} ],
"contactInfo" : {
"familyName" : "Cassini",
"fullName" : "Flavio Cassini",
"givenName" : "Flavio"
},
"organizations" : [ {
"name" : "DEVTECH .LLC",
"startDate" : "2015-03",
"title" : "President/Owner",
"current" : true
} ],
"demographics" : {
"locationDeduced" : {
"normalizedLocation" : "Boca Raton, United States",
"deducedLocation" : "Boca Raton, Florida, United States",
"city" : {
"name" : "Boca Raton"
},
"state" : {
"deduced" : true,
"name" : "Florida",
"code" : "FL"
},
"country" : {
"name" : "United States",
"code" : "US"
},
"continent" : {
"deduced" : true,
"name" : "North America"
},
"county" : {
"deduced" : true,
"name" : "Palm Beach"
},
"likelihood" : 1.0
},
"gender" : "Male",
"locationGeneral" : "Boca Raton, Florida, United States"
},
"socialProfiles" : [ {
"type" : "klout",
"typeId" : "klout",
"typeName" : "Klout",
"url" : "http://klout.com/DevTechServices",
"username" : "DevTechServices",
"id" : "91760869707035580"
}, {
"followers" : 67,
"following" : 67,
"type" : "linkedin",
"typeId" : "linkedin",
"typeName" : "LinkedIn",
"url" : "https://www.linkedin.com/in/devtechservices",
"username" : "devtechservices",
"id" : "428935547"
}, {
"bio" : "Student at Full Sail University",
"followers" : 5,
"following" : 36,
"type" : "twitter",
"typeId" : "twitter",
"typeName" : "Twitter",
"url" : "https://twitter.com/DevTechServices",
"username" : "DevTechServices",
"id" : "3245620291"
} ],
"digitalFootprint" : {
"scores" : [ {
"provider" : "klout",
"type" : "general",
"value" : 48
} ],
"topics" : [ {
"provider" : "klout",
"value" : "Bitcoin"
}, {
"provider" : "klout",
"value" : "Content Marketing"
}, {
"provider" : "klout",
"value" : "SAAS"
}, {
"provider" : "klout",
"value" : "Software"
}, {
"provider" : "klout",
"value" : "WordPress"
} ]
}
}
The short answer is that if $parsed_json represents an associative array of associative arrays, then it stands to reason that $parsed_json['photos'] is an associative array itself. To access the 'contactInfo' value inside it, you simply use $parsed_json['photos']['contactInfo'].

Mongo Db aggregate $lookup returns empty array

when trying to "JOIN" operation with $lookup but results count is ok but "as" document is empty
I have two collections and i need to get user details from subscribercol with user_id in employer_jobscol
subscribercol
{
"_id" : ObjectId("58187e7551d244640626d7e1"),
"type" : "job_seeker",
"firstname" : "vishnu",
"lastname" : "kumar pv",
"email_array" : {
"primary" : "test#test.com",
"secondary" : "test#test.test",
"verified" : false
},
"address_array" : {
"address" : "test address22d",
"streetname" : "test222d",
"pincode" : "test222d",
"city" : "dddd",
"state" : "ALASKA2d",
"country" : "Argentinad"
},
"phone_array" : {
"primary" : "",
"secondary" : "",
"verified" : ""
},
"languages" : [
"english",
"malayalam",
"english2"
]
}
employer_jobscol
{
"_id" : ObjectId("582ada6b51d244073e2a7541"),
"employer_id" : ObjectId("58187e7551d244640626d7e1"),
"job_id" : "testjob16946",
"job_title" : "Test Job 25",
"category" : "IT",
"vacancies" : "5",
"salary" : "200000",
"location" : "Kollam",
"employer_name" : "test test",
"mobile" : "9123456987",
"video" : "",
"image" : "",
"work_place" : "option1",
"email" : "test#test.test",
"skills" : [
"php"
],
"isActive" : true,
"applied_users" : [
{
"user_id" : ObjectId("581b364751d2445c311cf6f1"),
"accepted" : false
},
{
"user_id" : ObjectId("58187e7551d244640626d7e1"),
"accepted" : false
}
]
}
my database query here, (executed with Robomongo )
db.getCollection('employer_jobscol').aggregate([ {
$unwind: "$applied_users"
},
{
$lookup:
{
from: "subscribercol",
localField: "user_id",
foreignField: "_id",
as: "subscribercol_docs"
}
}
])
Result is
{
"_id" : ObjectId("582ada6b51d244073e2a7541"),
"employer_id" : ObjectId("58187e7551d244640626d7e1"),
"job_id" : "testjob16946",
"job_title" : "Test Job 25",
"category" : "IT",
"vacancies" : "5",
"salary" : "200000",
"location" : "Kollam",
"employer_name" : "test test",
"mobile" : "9123456987",
"video" : "",
"image" : "",
"work_place" : "option1",
"email" : "test#test.test",
"skills" : [
"php"
],
"isActive" : true,
"applied_users" : {
"user_id" : ObjectId("58187e7551d244640626d7e1"),
"accepted" : false
},
"subscribercol_docs" : []
}
here subscribercol_docs is empty array i need user info (name, address etc..),
Because there is no user_id field in local document its "applied_users.user_id"
Try this
db.getCollection('employer_jobscol').aggregate([ {
$unwind: "$applied_users"
},
{
$lookup:
{
from: "subscribercol",
localField: "applied_users.user_id", // <-- check here
foreignField: "_id",
as: "subscribercol_docs"
}
}
])

Elasticsearch geo-location search not returning results for miles unit

im using elasticsearch to return business near a users location.
If i search with a distance unit of kilometer 'km' i get expected results but if i use miles 'm' it return 0 hits
example of km request with hits
{
"sort" : [
{
"_geo_distance" : {
"location" : {
"lon": -0.11454850000000001,
"lat": 51.4911665
},
"order" : "asc",
"unit" : "km"
}
}
],
"query": {
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "1km",
"location" : {
"lon": -0.11454850000000001,
"lat": 51.4911665
}
}
}
}
}
}
1km = 0.6 miles so this query should return the same number of results as above but returns 0
{
"sort" : [
{
"_geo_distance" : {
"location" : {
"lon": -0.11454850000000001,
"lat": 51.4911665
},
"order" : "asc",
"unit" : "m"
}
}
],
"query": {
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "1m",
"location" : {
"lon": -0.11454850000000001,
"lat": 51.4911665
}
}
}
}
}
}
Any ideas why this might be?
You simply need to use the correct distance unit: m is for meters, and for miles you need to use mi
{
"sort" : [
{
"_geo_distance" : {
"location" : {
"lon": -0.11454850000000001,
"lat": 51.4911665
},
"order" : "asc",
"unit" : "mi" <--- here
}
}
],
"query": {
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "1mi", <--- here
"location" : {
"lon": -0.11454850000000001,
"lat": 51.4911665
}
}
}
}
}
}

How to combine a filter with distance for a search using Elasticsearch?

I have a elasticsearch question:
Here is my mapping below:
{
"9849asdasprofiles" : {
"mappings" : {
"profile" : {
"properties" : {
"activity" : {
"type" : "long"
},
"address" : {
"type" : "string"
},
"cPerson" : {
"type" : "string"
},
"category_id" : {
"type" : "long"
},
"city" : {
"type" : "string"
},
"country" : {
"type" : "string"
},
"created_at" : {
"properties" : {
"date" : {
"type" : "string"
},
"timezone" : {
"type" : "string"
},
"timezone_type" : {
"type" : "long"
}
}
},
"editors" : {
"properties" : {
"__cloner__" : {
"type" : "object"
},
"__initializer__" : {
"type" : "object"
},
"__isInitialized__" : {
"type" : "boolean"
}
}
},
"fax" : {
"type" : "string"
},
"foto_url" : {
"type" : "string"
},
"has_siegel" : {
"type" : "long"
},
"has_upgrade" : {
"type" : "long"
},
"hsnr" : {
"type" : "string"
},
"id" : {
"type" : "long"
},
"info_text" : {
"type" : "string"
},
"location" : {
"type" : "geo_point",
"fielddata" : {
"format" : "compressed",
"precision" : "3m"
}
},
"logo_url" : {
"type" : "string"
},
"name" : {
"type" : "string"
},
"phone" : {
"type" : "string"
},
"published" : {
"type" : "boolean"
},
"role_limit_article" : {
"type" : "boolean"
},
"role_limit_clicktracking" : {
"type" : "boolean"
},
"role_limit_contact_fax" : {
"type" : "boolean"
},
"role_limit_contact_mail" : {
"type" : "boolean"
},
"role_limit_contact_phone" : {
"type" : "boolean"
},
"role_limit_contact_website" : {
"type" : "boolean"
},
"role_limit_create_profile" : {
"type" : "boolean"
},
"role_limit_events" : {
"type" : "boolean"
},
"role_limit_following" : {
"type" : "boolean"
},
"role_limit_gallery" : {
"type" : "boolean"
},
"role_limit_images" : {
"type" : "boolean"
},
"role_limit_info_fields" : {
"type" : "boolean"
},
"role_limit_logo" : {
"type" : "boolean"
},
"role_limit_messages" : {
"type" : "boolean"
},
"role_limit_products" : {
"type" : "boolean"
},
"role_limit_view_follower" : {
"type" : "boolean"
},
"role_limit_visitors" : {
"type" : "boolean"
},
"role_limit_visittracking" : {
"type" : "boolean"
},
"siegel_url" : {
"type" : "string"
},
"slug" : {
"type" : "string"
},
"street" : {
"type" : "string"
},
"upgrade_level" : {
"type" : "long"
},
"upgrade_sort" : {
"type" : "integer"
},
"visible" : {
"type" : "boolean"
},
"website" : {
"type" : "string"
},
"zipcode" : {
"type" : "string"
}
}
}
}
}
}
For db-entries in the mapping above I want to get only the entries with defined IDs. The IDs are in an array. After filtering These items, then I want to run a distance search. So I ran this query below:
{
"index": "9849asdasprofiles",
"type": "profile",
"size": 30,
"from": 0,
"body": {
"query": {
"function_score": {
"functions": [
{
"linear": {
"location": {
"origin": "48.136833417046,11.570900696682",
"offset": "2km",
"scale": "1km"
}
}
}
],
"score_mode": "avg",
"boost_mode": "replace",
"query": {
"bool": {
"must": [
{
"term": {
"published": "1"
}
},
{
"match": {
"country": "DE"
}
}
],
"filter": {
"terms": {
"id": [
5336,
4955,
5488
]
}
}
}
}
}
},
"aggs": {
"rings": {
"geo_distance": {
"field": "location",
"origin": "48.136833417046,11.570900696682",
"distance_type": "arc",
"unit": "km",
"ranges": [
{
"to": 25
}
]
}
}
},
"script_fields": {
"distance": {
"lang": "groovy",
"params": {
"lat": 48.136833417046,
"lon": 11.570900696682
},
"script": "doc['location'].arcDistanceInKm(lat,lon)"
}
},
"sort": [
{
"upgrade_sort": {
"order": "desc"
}
},
{
"has_siegel": {
"order": "desc"
}
},
{
"_geo_distance": {
"location": {
"lat": 48.136833417046,
"lon": 11.570900696682
},
"order": "asc",
"unit": "km"
}
}
]
},
"fields": [
"_source",
"distance"
]
}
The problem is: The result contains entries with the specified IDs, but the distance filter doesn't affect the results.
Any Ideas as to how to do this?
Ok, I got it: The solution was really simple. I only had to change the filter part (in PHP) from
$params['body']['query']['function_score']['query']['bool']['filter']
to
$params['body']['query']['function_score']['filter']
But I couldn't find that part in the elastisearch documentation... :(

Categories