MongoDb query for getting count information after aggregation for more than one size from collecgtion - mongodb

What i am try to achieve is getting more than one size from collection.below query not working as expected.
shown below is collection.
{
"_id" : ObjectId("59e9c029c817c359508b4568"),
"client_id" : "20",
"device_details" : {
"type" : "others",
"name" : "Google Bot",
"os" : null,
"os_version" : null,
"browser" : null,
"browser_version" : null,
"user_agent" : "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
"width" : NumberLong("1024"),
"height" : NumberLong("1024"),
"fingerid" : "c714d8f7eb7d216693c0ddd06cfc0940",
"canvasfingerid" : "84f1922a78572180c7f29f938486c1db",
"webglfingerid" : "24700f9f1986800ab4fcc880530dd0ed",
"hardwarefingerid" : "431171c98112e1f0dfb3b40f617111f9",
"platformos" : "Linux x86_64",
"adblock" : "false",
"donot" : "unknown",
"liedlanguage" : "false",
"liedos" : "false",
"liedbrowser" : "false",
"ratio" : NumberLong("1"),
"depth" : NumberLong("24"),
"language" : "en-US",
"liedresolution" : "false",
"timezoneoffset" : "420",
"regularplugin" : "No plugins found",
"localstorage" : "true",
"sessionstorage" : "true",
"touchsupport" : "false",
"canvas" : "Tracked",
"webgl" : "Unknown",
"hardwareconc" : "8",
"referrer" : null,
"referrer_url" : null,
"scrorientation" : "landscape-primary"
},
"ip_list" : [
"66.249.66.146",
"66.249.66.21"
],
"ip_details" : [
{
"ip_address" : "66.249.66.146",
"latitude" : 37.41919999999999,
"longitude" : -122.0574,
"city" : "Mountain View",
"postal_code" : "94043",
"country_code" : "US",
"country_name" : "United States",
"continent_code" : "NA",
"created_date" : ISODate("2017-10-20T14:51:45.176+05:30")
},
{
"ip_address" : "66.249.66.21",
"latitude" : 37.41919999999999,
"longitude" : -122.0574,
"city" : "Mountain View",
"postal_code" : "94043",
"country_code" : "US",
"country_name" : "United States",
"continent_code" : "NA",
"created_date" : ISODate("2017-10-24T08:27:24.385+05:30")
}
],
"urls" : [
{
"host" : {
"time" : ISODate("2017-10-20T14:51:45.197+05:30"),
"url" : "http://www.indianmobileprices.com/index.php/mobile/info/9-APPLE/7062-APPLE-iPhone+7+/dehradun"
}
},
{
"host" : {
"time" : ISODate("2017-10-24T08:27:24.405+05:30"),
"url" : "http://www.indianmobileprices.com/brand/mobiles/10-LENOVO/bhubaneswar"
}
}
],
"created_date" : ISODate("2017-10-24T08:27:24.405+05:30"),
"current_timestamp" : NumberLong("1508491305"),
"traffic" : null,
"traffic_url" : [
{
"url" : "",
"date" : ISODate("2017-10-20T14:51:45.197+05:30")
},
{
"url" : "",
"date" : ISODate("2017-10-24T08:27:24.314+05:30")
},
{
"url" : "",
"date" : ISODate("2017-10-24T08:27:24.578+05:30")
}
],
"returning_user" : NumberLong("1"),
"returninguser" : "yes",
"updated_timestamp" : NumberLong("1508813844"),
"multisession" : NumberLong("2")
},
Here is the query i have used.
db.audience.aggregate([
{"$group":{
"_id":"$ip_details.country_name",
"device_information":{
"$addToSet":{
"ipaddress":"$ip_details.ip_address",
"country_name":"$ip_details.country_name",
"device_name":"$device_details.name",
"device_type":"$device_details.type",
"device_os":"$device_details.os",
"devicen_osversion":"$device_details.os_version"
}
},
"count":{"$sum":1}
}},
{ "$project":{
"device_information":1,
"_id":0,
"countrySize":{ "$size":"$device_information.country_name" },
"desktopSize":{ "$size":'$device_information.device_type' }
}},
{ "$match":{ "countrySize":{"$gt":1} }},
{ "$match":{"desktopSize":{"$device_information.device_type":"desktop"} }}
])
For that i could not get expected result is given below.need to change query for the result.
/* 1 */
{
"countrySize" : NumberInt("4"),
"desktopSize" : NumberInt("2"),
"device_information" : [
{
"country_name" : [
"Singapore"
],
"device_name" : "generic web browser",
"device_os" : "Windows",
"device_type" : "desktop",
"devicen_osversion" : "10",
"ipaddress" : [
"52.220.245.83"
]
},
{
"country_name" : [
"Singapore"
],
"device_name" : "Apple iPhone",
"device_os" : "iOS",
"device_type" : "others",
"devicen_osversion" : "10.3.3",
"ipaddress" : [
"185.89.218.227"
]
},
{
"country_name" : [
"Singapore"
],
"device_name" : "generic web browser",
"device_os" : "Mac OS X",
"device_type" : "desktop",
"devicen_osversion" : "10.12.6",
"ipaddress" : [
"121.7.242.239"
]
},
{
"country_name" : [
"Singapore"
],
"device_name" : "Samsung Galaxy Note 4",
"device_os" : "Android",
"device_type" : "mobile",
"devicen_osversion" : "6.0.1",
"ipaddress" : [
"220.255.108.72"
]
}
]
},
I need query for results that is given above.

Related

$map upto three nested array mongodb aggregation

I´m facing a challenge here. I have this collection here
{
"_id" : ObjectId("5e0ff6d424f9fc12bc3d9464"),
"name" : "Pizzaria Don Juan",
"active" : true,
"branches" : [
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19cafc31d60216b8dbd649"),
"name" : "Parque da Mooca",
"address" : "Rua Dianópolis",
"addressNumber" : 1283,
"federalId" : "10.445.089/0001-44",
"complement" : "Ap 55",
"postalCode" : "03126-007",
"coveredArea" : 0,
"neighborhood" : "Parque da Mooca",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : false,
"city" : "Mococa",
"state" : "RJ",
"emails" : [ ],
"phones" : [ ],
"daysWeek" : [ ],
"socialMedias" : [ ],
"paymentTerms" : [ ],
"sections" : [ ]
},
{
"location" : {
"type" : "Point",
"coordinates" : [ ]
},
"_id" : ObjectId("5e19c9a531d60216b8dbd639"),
"name" : "Principal",
"address" : "Rua Nicolau Filizola",
"addressNumber" : null,
"federalId" : "10.445.089/0001-53",
"complement" : "",
"postalCode" : "05547-010",
"coveredArea" : 0,
"neighborhood" : "Jardim Rosa Maria",
"deliveryTime" : 0,
"deliveryRate" : 0,
"standard" : true,
"city" : "São Paulo",
"state" : "SP",
"emails" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd643"),
"name" : "Contato",
"address" : "contato#pizzariadonjuan.com.br"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd642"),
"name" : "Contato2",
"address" : "contato2#pizzariadonjuan.com.br"
}
],
"phones" : [
{
"_id" : ObjectId("5e19ca9531d60216b8dbd645"),
"name" : "Principal",
"number" : "(11) 99740-2216"
},
{
"_id" : ObjectId("5e19ca9531d60216b8dbd644"),
"name" : "Secundario",
"number" : "(11) 2562-2759"
}
],
"daysWeek" : [
{
"_id" : ObjectId("5e1cf99741c52d4a587a9162"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a124a17fd054900a1afb2")
},
{
"_id" : ObjectId("5e1cf99741c52d4a587a9161"),
"startsAt" : 0,
"endsAt" : 0,
"opens" : false,
"dayWeekId" : ObjectId("5e1a126817fd054900a1afb3")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a9170"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a126e17fd054900a1afb4")
},
{
"_id" : ObjectId("5e1b8fac96516432845e364c"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127517fd054900a1afb5")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916f"),
"startsAt" : 64980000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a127a17fd054900a1afb6")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916e"),
"startsAt" : 64800000,
"endsAt" : 82800000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a23f8bf353f493c74e8ae")
},
{
"_id" : ObjectId("5e1cfbed41c52d4a587a916d"),
"startsAt" : 61380000,
"endsAt" : 83154000,
"opens" : true,
"dayWeekId" : ObjectId("5e1a2407bf353f493c74e8af")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e1d082641c52d4a587a9191"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "rewrwerwerwerwerwerwerwer"
}
],
"paymentTerms" : [
{
"_id" : ObjectId("5e1d143041c52d4a587a91b7"),
"paymentTermId" : ObjectId("5e1a2277bf353f493c74e8a7")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b6"),
"paymentTermId" : ObjectId("5e1a228cbf353f493c74e8a8")
},
{
"_id" : ObjectId("5e1d143041c52d4a587a91b5"),
"paymentTermId" : ObjectId("5e1a229ebf353f493c74e8a9")
}
],
"sections" : [
{
"_id" : ObjectId("5e1e535441c52d4a587a9208"),
"name" : "Camisetas",
"products" : [
{
"_id" : ObjectId("5e1e662f044582129844ffd5"),
"name" : "DonJuan M",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("2020-01-15T01:08:49.552Z"),
"validTo" : ISODate("2020-01-15T01:08:49.552Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20ec889c05f229a484ea3d"),
"name" : "Imãs",
"products" : [
{
"_id" : ObjectId("5e20ec889c05f229a484ea3e"),
"name" : "Imã",
"description" : "Imã",
"quantityAvailable" : 0,
"image" : "",
"price" : 0,
"validFrom" : ISODate("0001-01-01T00:00:00Z"),
"validTo" : ISODate("9999-12-31T00:00:00Z"),
"enabled" : true
}
]
}
]
}
],
"users" : [
{
"_id" : ObjectId("5e10fc2adc147a373c312144")
},
{
"_id" : ObjectId("5e11ff8003eb832ef84342a6")
}
],
"socialMedias" : [
{
"_id" : ObjectId("5e165672a2204b49c892db74"),
"socialMediaId" : ObjectId("5e10089a3330ad05d4e1867d"),
"url" : "uuuutt"
},
{
"_id" : ObjectId("5e15385fb3a0aa1004ac3598"),
"socialMediaId" : ObjectId("5e1009043330ad05d4e1867f"),
"url" : "jkkjkjkjkjk"
}
],
"sections" : [
{
"_id" : ObjectId("5e15313b2e985e16ec4e7413"),
"name" : "Bebidas",
"products" : [
{
"_id" : ObjectId("5e1e6381044582129844ffc2"),
"name" : "Coca Cola Zero 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 18.39,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e6381044582129844ffc3"),
"name" : "Coca Cola 2 Litros",
"description" : "",
"quantityAvailable" : 0,
"image" : "",
"price" : 21.42,
"validFrom" : ISODate("1970-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
},
{
"_id" : ObjectId("5e1e662f044582129844ffda"),
"name" : "Cerveja Heineken Lata 350ml",
"description" : "Cerveja Heineken Lata 350ml",
"quantityAvailable" : 0,
"image" : "volkswagen-polo.jpg",
"price" : 1.55,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : ISODate("1970-01-01T00:00:00Z"),
"enabled" : true
}
]
},
{
"_id" : ObjectId("5e20e8de9c05f229a484ea27"),
"name" : "Esfihas",
"products" : [
{
"_id" : ObjectId("5e20e8de9c05f229a484ea28"),
"name" : "Esfiha de carne",
"description" : "Esfiha de carne",
"quantityAvailable" : 0,
"image" : "",
"price" : 5,
"validFrom" : ISODate("2020-01-01T00:00:00Z"),
"validTo" : null,
"enabled" : true
}
]
}
],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd23991918424c8d7c3b"),
"name" : "Pizza Ruth",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
{
"_id" : ObjectId("5e0ffd3d991918424c8d7c3c"),
"name" : "Feijão de Corda",
"active" : true,
"users" : [ ],
"socialMedias" : [ ],
"branches" : [ ],
"sections" : [ ],
"__v" : 0
}
The fields validFrom and validTo (Date fields) from the collection products nested in branches.sections need to be converted to the format yyyy-mm-dd. I can do that with this aggregation pipeline:
{ $unwind: { path: "$branches.sections", preserveNullAndEmptyArrays: true } },
{
"$addFields": {
"branches.sections.products": {
$map: {
input: "$branches.sections.products",
as: "product",
in: {
'_id': "$$product._id",
'name': "$$product.name",
'description': "$$product.description",
'quantityAvailable': "$$product.quantityAvailable",
'image': "$$product.image",
'imageUrl': "$$product.imageUrl",
'price': "$$product.price",
'validFrom' : {"$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
'validTo' : {"$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }},
'enabled': "$$product.enabled",
}
}
}
}
}
I can successfully convert those date fields, but I need now to "re-unwind" the array products, in order to be just like before the unwind.
Any clue in how to proceed? Or even a different way to format those dates without having to unwind? Tried dozens of ways of $group, but without any success.
You just need to $map over each nested array to drill upload the validTo and validFrom field
.aggregate([
{ "$addFields": {
"branches": {
"$map": {
"input": "$branches",
"as": "branch",
"in": {
"$mergeObjects": [
"$$branch",
{ "section": {
"$map": {
"input": "$$branch.sections",
"as": "section",
"in": {
"$mergeObjects": [
"$$section",
{ "product": {
"$map": {
"input": "$$section.products",
"as": "product",
"in": {
"$mergeObjects": [
"$$product",
{
"validFrom": { "$dateToString": { "date": "$$product.validFrom", "format": "%Y-%d-%m" }},
"validTo": { "$dateToString": { "date": "$$product.validTo", "format": "%Y-%d-%m" }}
}
]
}
}
}}
]
}
}
}}
]
}
}
}
}}
])
MongoPlayground

String to ISO Date

I've looked this up a few times and no answer has worked so far. I want to turn a string date into an ISODate - I don't want it converted to or from UTC, I just want to make the date value which is stored as string to be stored as a date.
I don't want UTC because I want to query against and calculate based upon a time of day (example: 12pm) anywhere in the world and I'm summing by hour, day, week and month and comparing data across many countries based upon local time.
Currently I have a date as a string which I want to add to a new document with a new name:
"transaction_date": "$object_raw_origin_data.register_sales.sale_date"
The date value as string below is shown as:
"sale_date" : "2018-03-13 20:05:46"
I want it to be: "transaction_date" : ISODate("2018-03-13 20:05:46")
The date and time must read 2018-03-13 20:05:46 not converted to UTC.
Thanks, Matt
Origin Data JSON
{
"object_category" : "application",
"object_type" : "register-sales-24-months",
"object_origin" : "vend",
"tenant_uuid" : "00000000-0000-0009-9999-999999999999",
"party_uuid" : "8d519765-05d2-469f-ad35-d7a22fa9df2f",
"subscription_uuid" : "0",
"connection_uuid" : "6ed9bd79-d9c5-4296-a821-7e15b1c69e6c",
"status" : "",
"object_created" : ISODate("2018-03-15T21:40:57.158+0000"),
"object_raw_origin_data" : {
"pagination" : {
"results" : NumberInt(75964),
"page" : NumberInt(1),
"page_size" : NumberInt(200),
"pages" : NumberInt(380)
},
"register_sales" : {
"id" : "776a66f2-993c-b372-11e8-26f9d3c1bdde",
"source" : "USER",
"source_id" : "",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"market_id" : "3",
"customer_id" : "02d59481-b67d-11e5-f667-b08185e8f6d5",
"customer_name" : "",
"customer" : {
"id" : "02d59481-b67d-11e5-f667-b08185e8f6d5",
"name" : "",
"customer_code" : "WALKIN",
"customer_group_id" : "02d59481-b67d-11e5-f667-b08185e893f8",
"customer_group_name" : "All Customers",
"updated_at" : "2016-01-01 12:16:44",
"deleted_at" : "",
"balance" : "0",
"year_to_date" : "0",
"date_of_birth" : "",
"sex" : "",
"custom_field_1" : "",
"custom_field_2" : "",
"custom_field_3" : "",
"custom_field_4" : "",
"note" : "",
"contact" : {
}
},
"user_id" : "02d59481-b655-11e5-f667-dca974edc4ea",
"user_name" : "Alvaro Velosa",
"sale_date" : "2018-03-13 20:05:46",
"created_at" : "2018-03-13 20:06:00",
"updated_at" : "2018-03-13 20:06:00",
"total_price" : 4.5,
"total_cost" : 3.34,
"total_tax" : NumberInt(0),
"tax_name" : "No Tax",
"note" : "",
"status" : "CLOSED",
"short_code" : "wqgsgi",
"invoice_number" : "Masonic2108Temple",
"accounts_transaction_id" : "",
"return_for" : "",
"register_sale_products" : [
{
"id" : "776a66f2-993c-b372-11e8-26f9e92cb9bc",
"product_id" : "02dcd191-ae55-11e7-f130-9d4f4bcd91b1",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"sequence" : "0",
"handle" : "LAGERDRAUGHT300",
"sku" : "10287",
"name" : "LAGER DRAUGHT £3.00",
"quantity" : NumberInt(1),
"price" : 3.5,
"cost" : 2.74,
"price_set" : NumberInt(0),
"discount" : NumberInt(0),
"loyalty_value" : NumberInt(0),
"tax" : NumberInt(0),
"tax_id" : "02d59481-b67d-11e5-f667-b08185ec2871",
"tax_name" : "No Tax",
"tax_rate" : NumberInt(0),
"tax_total" : NumberInt(0),
"price_total" : 3.5,
"display_retail_price_tax_inclusive" : "0",
"status" : "CONFIRMED",
"attributes" : [
{
"name" : "line_note",
"value" : ""
}
]
},
{
"id" : "776a66f2-993c-b372-11e8-26f9e98104e0",
"product_id" : "02dcd191-ae55-11e7-f130-9d50e948a0b5",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"sequence" : "0",
"handle" : "SOFTDRINK",
"sku" : "10292",
"name" : "SOFT DRINK",
"quantity" : NumberInt(1),
"price" : NumberInt(1),
"cost" : 0.6,
"price_set" : NumberInt(0),
"discount" : NumberInt(0),
"loyalty_value" : NumberInt(0),
"tax" : NumberInt(0),
"tax_id" : "02d59481-b67d-11e5-f667-b08185ec2871",
"tax_name" : "No Tax",
"tax_rate" : NumberInt(0),
"tax_total" : NumberInt(0),
"price_total" : NumberInt(1),
"display_retail_price_tax_inclusive" : "0",
"status" : "CONFIRMED",
"attributes" : [
{
"name" : "line_note",
"value" : ""
}
]
}
],
"totals" : {
"total_tax" : NumberInt(0),
"total_price" : 4.5,
"total_payment" : 4.5,
"total_to_pay" : NumberInt(0)
},
"register_sale_payments" : [
{
"id" : "776a66f2-993c-b372-11e8-26f9eab2cb46",
"payment_type_id" : "1",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"retailer_payment_type_id" : "02d59481-b655-11e5-f667-b0a23bc0e7bc",
"name" : "Cash",
"label" : "Account Customer",
"payment_date" : "2018-03-13 20:05:46",
"amount" : NumberInt(10)
},
{
"id" : "776a66f2-993c-b372-11e8-26f9eab6b21a",
"payment_type_id" : "1",
"register_id" : "02dcd191-ae55-11e6-edd8-ec8dce1d9e1c",
"retailer_payment_type_id" : "02d59481-b655-11e5-f667-b0a23bc0e7bc",
"name" : "Cash",
"label" : "Account Customer",
"payment_date" : "2018-03-13 20:05:46",
"amount" : -5.5
}
]
}
}
}
Thanks for the help from #Saleem and #Krishna however, I have tried to create an ISODate using a $concat of $substr from a string and it isn't working.
db.Vend_raw_transactions.aggregate(
[{
"$project": {
"object_origin": "$object_origin",
"company": "$party_uuid",
"connection": "$connection_uuid",
"object_creation_date": "$object_created",
// "transaction_date": "$object_raw_origin_data.register_sales.sale_date",
"transaction_date": {
"$dateFromString": {
"dateString": {
"$concat": [
"$substr": [ "$object_raw_origin_data.register_sales.sale_date", 0, 10 ],
"T",
"$substr": [ "$object_raw_origin_data.register_sales.sale_date", 11, 9]
]
}
}
},
"transaction_gross_value": {
"$add": [
"$object_raw_origin_data.register_sales.total_price",
"$object_raw_origin_data.register_sales.total_tax"
]
},
"transaction_net_value": "$object_raw_origin_data.register_sales.total_price",
"transaction_tax_value": "$object_raw_origin_data.register_sales.total_tax",
"transaction_cost_value": "$object_raw_origin_data.register_sales.total_cost",
"object_class": "goods-service-transaction",
"object_origin_category": "point-of-sale",
"object_type": "receipt",
"object_origin_type": "offline",
"transaction_reference": "$object_raw_origin_data.register_sales.invoice_number",
"transaction_status": "$object_raw_origin_data.register_sales.status",
"transaction_currency": "GBP",
"party_name": "$object_raw_origin_data.register_sales.customer.customer_name",
"party_identifier": "$object_raw_origin_data.register_sales.customer.customer_code",
"staff_identifier": "$object_raw_origin_data.register_sales.user_id",
"staff_name": "$object_raw_origin_data.register_sales.user_name",
"line_items" : {
"$map": {
"input": "$object_raw_origin_data.register_sales.register_sale_products",
"as" : "product",
"in": {"item_name": "$$product.name",
"item_system_id": "$$product.id",
"item_identifier": "$$product.sku",
"item_category" : "sales-revenue",
"item_quantity" : "$$product.quantity",
"item_net_unit_sale_value" : "$$product.price",
"item_net_unit_discount_value" : "$$product.discount",
"item_net_unit_member_value" : "$$product.loyalty_value",
"item_net_unit_cost_value" : "$$product.cost",
"item_unit_tax_value" : "$$product.tax",
"item_price_list_reference" : "$$product.price_set",
"item_total_sale_value" : "$$product.price_total",
"item_total_tax_value" : "$$product.tax_total"
}
}
}
}
}
// ,{"$out": "9SP_Source" }
])
I cannot work out why this isn't working, it seems like it should - I'm creating a new string based upon an existing string value and adding a T in the middle but it doesn't recognise $DateFromString. Thanks
Error Message
{
"message" : "Unrecognized expression '$dateFromString'",
"stack" : "MongoError: Unrecognized expression '$dateFromString'" +
"at queryCallback (C:\Users\mattl\AppData\Local\Programs\nosqlbooster4mongo\resources\app.asar\node_modules\mongodb-core\lib\cursor.js:223:25)" +
"at C:\Users\mattl\AppData\Local\Programs\nosqlbooster4mongo\resources\app.asar\node_modules\mongodb-core\lib\connection\pool.js:541:18" +
"at _combinedTickCallback (internal/process/next_tick.js:131:7)" +
"at process._tickCallback (internal/process/next_tick.js:180:9)",
"name" : "MongoError",
"ok" : 0,
"errmsg" : "Unrecognized expression '$dateFromString'",
"code" : 168,
"codeName" : "InvalidPipelineOperator"
}
I've managed to make another string using the below script but $dateFromString unrecognised
db.Vend_raw_transactions.aggregate(
[{
"$project": {
"origin_date": "$object_raw_origin_data.register_sales.sale_date",
"transaction_date": {
"$substr": [ "$object_raw_origin_data.register_sales.sale_date", 0, 10 ]
},
"transaction_time": {
"$substr": [ "$object_raw_origin_data.register_sales.sale_date", 11, 9 ]
},
"new_string_date": {
"$concat" :[
{"$substr": [ "$object_raw_origin_data.register_sales.sale_date", 0, 10 ]},
"T",
{"$substr": [ "$object_raw_origin_data.register_sales.sale_date", 11, 9 ]}]
}
}
}
])
Thanks

MongoDB how we can group data by field value

I have the following query, what I want is to have a combined group of custom group field names, with field value.
db.getCollection('mycollection').aggregate([
{"$match":{
"expireDate":{"$gte":"2018-02-06T00:00:00.000Z"},
"publishDate":{"$lte":"2018-02-06T00:00:00.000Z"},
"isPublished":true,"isDrafted":false,
"deletedAt":{"$eq":null},"deleted":false
}},
{"$group":{
"twentyFourHourAgo":{
"$sum":{
"$cond":[
{"$gt":["$publishDate","2018-02-04T08:48:16.892Z"]},1,0
]
}
},
"fortyEightHourAgo":{
"$sum":{
"$cond":[
{"$gt":["$publishDate","2018-02-01T08:48:16.892Z"]},1,0
]
}
},
"thirtyDaysAgo":{
"$sum":{
"$cond":[
{"$gt":["$publishDate","2017-12-31T08:48:16.892Z"]},1,0
]
}
},
"_id":{
"position":{"$ifNull":["$position","Unknown"]},
"workType":{"$ifNull":["$workType","Unknown"]},
"functionalArea":{"$ifNull":["$functionalArea","Unknown"]},
"minimumEducation":{"$ifNull":["$minimumEducation","Unknown"]},
"gender":{"$ifNull":["$gender","Unknown"]},
"contractType":{"$ifNull":["$contractType","Unknown"]},
"locations":{"$ifNull":["$locations","Unknown"]},
"requiredLanguages":{"$ifNull":["$requiredLanguages","Unknown"]},
"company":{"$ifNull":["$company.name","Unknown"]}},"count":{"$sum":1}
}
},
{"$group":{
"_id":null,
"twentyFourHourAgo":{
"$sum":"twentyFourHourAgo"
},
"fortyEightHourAgo":{
"$sum":"$fortyEightHourAgo"
},
"thirtyDaysAgo":{
"$sum":"$thirtyDaysAgo"
},
"position":{"$addToSet":{"Name":"$_id.position","Count":"$count"}},
"workType":{"$addToSet":{"Name":"$_id.workType","Count":"$count"}},
"functionalArea":{
"$addToSet":{"Name":"$_id.functionalArea","Count":"$count"}
},
"minimumEducation":{
"$addToSet":{"Name":"$_id.minimumEducation","Count":"$count"}
},
"gender":{"$addToSet":{"Name":"$_id.gender","Count":"$count"}},"contractType":{"$addToSet":{"Name":"$_id.contractType","Count":"$count"}},"locations":{"$addToSet":{"Name":"$_id.locations","Count":"$count"}},"requiredLanguages":{"$addToSet":{"Name":"$_id.requiredLanguages","Count":"$count"}},"company":{"$addToSet":{"Name":"$_id.company","Count":"$count"}}}}]
)
my document inside collection schema is like:
/* 1 */
{
"_id" : ObjectId("59e4540bf14f1607b90ffb81"),
"vacancyNumber" : "1",
"position" : "Software Tester",
"publishDate" : ISODate("2018-01-02T00:00:00.000Z"),
"expireDate" : ISODate("2018-05-29T00:00:00.000Z"),
"yearsOfExperience" : 40,
"minimumEducation" : "Doctorate",
"functionalArea" : "Education",
"company" : {
"id" : ObjectId("59e453fbf14f1607b90ffb80"),
"name" : "First Company",
"profile" : "profile",
"logo" : {
"container" : "companyFiles",
"name" : "abbbff58cd3fda2c59ab2ee620ea5aa0",
"mime" : ".png",
"size" : 5806
}
},
"durations" : {
"years" : 3,
"months" : 4
},
"probationPeriod" : {
"duration" : 34,
"unit" : "month"
},
"salary" : {
"minSalary" : 1000,
"maxSalary" : 2000,
"currency" : "USD",
"period" : "monthly",
"isNegotiable" : true
},
"locations" : [
"Germany",
"Itly",
"Iran"
],
"canApplyOnline" : true,
"skills" : [
"Skill1",
"Skill2",
"Skill3",
"Skill4"
],
"requiredLanguages" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"keywords" : [
"Key1",
"Key2"
],
"deleted" : false,
"deletedAt" : null,
"isDrafted" : false,
"isPublished" : true,
"requiresTravel" : true,
"gender" : "male",
"nationalities" : [
"afghan"
],
"workType" : "Full Time",
"contractType" : "Permanent",
}
/* 2 */
{
"_id" : ObjectId("59f9402e05d04ebe5653d98f"),
"vacancyNumber" : "1",
"position" : "Software Engineer",
"publishDate" : ISODate("2018-01-03T00:00:00.000Z"),
"expireDate" : ISODate("2018-11-10T00:00:00.000Z"),
"yearsOfExperience" : 40,
"minimumEducation" : "Doctorate",
"functionalArea" : "Education",
"company" : {
"id" : ObjectId("59e453fbf14f1607b90ffb80"),
"name" : "First Company",
"profile" : "profile",
"logo" : {
"container" : "logo container",
"name" : "logo name",
"mime" : "logo mime type",
"size" : 1
}
},
"durations" : {
"years" : 3,
"months" : 4
},
"probationPeriod" : {
"duration" : 34,
"unit" : "month"
},
"salary" : {
"minSalary" : 1000,
"maxSalary" : 2000,
"currency" : "USD",
"period" : "monthly",
"isNegotiable" : true
},
"locations" : [
"Afghanistan",
"Itly",
"Iran"
],
"skills" : [
"Skill1",
"Another Skill"
],
"requiredLanguages" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"keywords" : [
"Keyword",
"Key1"
],
"deleted" : false,
"deletedAt" : null,
"isDrafted" : false,
"isPublished" : true,
"gender" : "male",
"nationalities" : [
"afghan",
"iranian"
],
"workType" : "Full Time",
"contractType" : "Short-Term",
}
/* 3 */
{
"_id" : ObjectId("5a03235234f7504f13970abd"),
"vacancyNumber" : "1",
"position" : "Software Tester",
"publishDate" : ISODate("2017-10-10T00:00:00.000Z"),
"expireDate" : ISODate("2018-11-25T00:00:00.000Z"),
"yearsOfExperience" : 40,
"minimumEducation" : "Doctorate",
"functionalArea" : "IT Software",
"company" : {
"id" : ObjectId("59e453fbf14f1607b90ffb80"),
"name" : "My First Company",
"profile" : "profile",
"logo" : {
"container" : "logo container",
"name" : "logo name",
"mime" : "logo mime type",
"size" : 1
}
},
"durations" : {
"years" : 3,
"months" : 4
},
"probationPeriod" : {
"duration" : 34,
"unit" : "month"
},
"salary" : {
"minSalary" : 1000,
"maxSalary" : 2000,
"currency" : "USD",
"period" : "monthly",
"isNegotiable" : true
},
"locations" : [
"Germany",
"Itly",
"Iran"
],
"skills" : [
"Skill1",
"Test Skill"
],
"requiredLanguages" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"keywords" : [
"Test Key",
"Keyword"
],
"deleted" : false,
"deletedAt" : null,
"isDrafted" : false,
"isPublished" : true,
"gender" : "female",
"nationalities" : [
"afghan"
],
"workType" : "Part Time",
"contractType" : "Permanent",
}
Now I want to count the group of data by my custom expression check 'twentyFourHourAgo, fortyEightHourAgo, thirtyDaysAgo', and also by the value of a field (functionalArea, position, locations, keywords, workType).
My current query result is
{
"_id" : null,
"twentyFourHourAgo" : 0,
"fortyEightHourAgo" : 0.0,
"thirtyDaysAgo" : 2.0,
"position" : [
{
"Name" : "Software Engineer",
"Count" : 1.0
},
{
"Name" : "Software Tester",
"Count" : 1.0
}
],
"workType" : [
{
"Name" : "Full Time",
"Count" : 1.0
},
{
"Name" : "Part Time",
"Count" : 1.0
}
],
"functionalArea" : [
{
"Name" : "Education",
"Count" : 1.0
},
{
"Name" : "IT Software",
"Count" : 1.0
}
],
"minimumEducation" : [
{
"Name" : "Doctorate",
"Count" : 1.0
}
],
"gender" : [
{
"Name" : "male",
"Count" : 1.0
},
{
"Name" : "female",
"Count" : 1.0
}
],
"contractType" : [
{
"Name" : "Short-Term",
"Count" : 1.0
},
{
"Name" : "Permanent",
"Count" : 1.0
}
],
"locations" : [
{
"Name" : [
"Afghanistan",
"Itly",
"Iran"
],
"Count" : 1.0
},
{
"Name" : [
"Germany",
"Itly",
"Iran"
],
"Count" : 1.0
}
],
"requiredLanguages" : [
{
"Name" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"Count" : 1.0
}
],
"company" : [
{
"Name" : "First Company",
"Count" : 1.0
},
{
"Name" : "My First Company",
"Count" : 1.0
}
]
}
As you see, I have three document that has following properties:
Two document that has the same position Software Tester, but query return 1 Software Tester (It means if I have multiple documents that have some common values in specific columns, their count result is wrong). The same problem exists for other fields 'contractType, workType, etc...'.
In array-type fields such as locations, my first document has Germany, Italy, Iran values in locations array, my second document has Afghanistan, Italy, Iran, and my third document has Germany, Italy, Iran. But query result is like this:
"locations" : [
{
"Name" : [
"Afghanistan",
"Itly",
"Iran"
],
"Count" : 1.0
},
{
"Name" : [
"Germany",
"Itly",
"Iran"
],
"Count" : 1.0
}
],
This should be like: Germany => 2, Italy,Iran => 3, and Afghanistan => 1
The same problem exists for other array type fields.
This give you what you were asking:
db.getCollection('foo').aggregate([
{"$match":{
"expireDate":{"$gte": ISODate("2018-01-02T00:00:00.000Z")},
"publishDate":{"$lte": ISODate("2018-05-29T00:00:00.000Z")},
"isPublished":true,"isDrafted":false,
"deletedAt":{"$eq":null},
"deleted":false
}},
{"$group":{
"twentyFourHourAgo":{
"$sum":{
"$cond":[
{"$gte":["$publishDate", ISODate("2018-01-02T00:00:00.000Z")]},1,0
]
}
},
"fortyEightHourAgo":{
"$sum":{
"$cond":[
{"$gte":["$publishDate", ISODate("2018-01-02T00:00:00.000Z")]},1,0
]
}
},
"thirtyDaysAgo":{
"$sum":{
"$cond":[
{"$gte":["$publishDate", ISODate("2018-01-02T00:00:00.000Z")]},1,0
]
}
},
"_id":{
"$ifNull":["$functionalArea","Unknown"]
},
/* Changes start from here */
"count" : { "$sum" : 1 } } },
{ "$group" : {
"_id" : "null", "fortyEightHourAgo" : { "$sum" : "$fortyEightHourAgo"},
"thirtyDaysAgo" : { "$sum" : "$thirtyDaysAgo"},
"twentyFourHourAgo" : { "$sum" : "$twentyFourHourAgo"},
"functionalArea" : { "$addToSet" : { "Name": "$_id", "Count" : "$count" } } }}
])
Output:
{
"_id" : null,
"fortyEightHourAgo" : 3.0,
"thirtyDaysAgo" : 3.0,
"twentyFourHourAgo" : 3.0,
"functionalArea" : [
{
"Name" : "Education",
"Count" : 1.0
},
{
"Name" : "IT Software",
"Count" : 2.0
}
]
}

MongoDB group by multiple fields in a way to not affect each other result

I have the following query, what I want is to have a combined group of custom group field names, with field value.
db.getCollection('mycollection').aggregate([
{"$match":{
"expireDate":{"$gte":"2018-02-06T00:00:00.000Z"},
"publishDate":{"$lte":"2018-02-06T00:00:00.000Z"},
"isPublished":true,"isDrafted":false,
"deletedAt":{"$eq":null},"deleted":false
}},
{"$group":{
"twentyFourHourAgo":{
"$sum":{
"$cond":[
{"$gt":["$publishDate","2018-02-04T08:48:16.892Z"]},1,0
]
}
},
"fortyEightHourAgo":{
"$sum":{
"$cond":[
{"$gt":["$publishDate","2018-02-01T08:48:16.892Z"]},1,0
]
}
},
"thirtyDaysAgo":{
"$sum":{
"$cond":[
{"$gt":["$publishDate","2017-12-31T08:48:16.892Z"]},1,0
]
}
},
"_id":{
"position":{"$ifNull":["$position","Unknown"]},
"workType":{"$ifNull":["$workType","Unknown"]},
"functionalArea":{"$ifNull":["$functionalArea","Unknown"]},
"minimumEducation":{"$ifNull":["$minimumEducation","Unknown"]},
"gender":{"$ifNull":["$gender","Unknown"]},
"contractType":{"$ifNull":["$contractType","Unknown"]},
"locations":{"$ifNull":["$locations","Unknown"]},
"requiredLanguages":{"$ifNull":["$requiredLanguages","Unknown"]},
"company":{"$ifNull":["$company.name","Unknown"]}},"count":{"$sum":1}
}
},
{"$group":{
"_id":null,
"twentyFourHourAgo":{
"$sum":"twentyFourHourAgo"
},
"fortyEightHourAgo":{
"$sum":"$fortyEightHourAgo"
},
"thirtyDaysAgo":{
"$sum":"$thirtyDaysAgo"
},
"position":{"$addToSet":{"Name":"$_id.position","Count":"$count"}},
"workType":{"$addToSet":{"Name":"$_id.workType","Count":"$count"}},
"functionalArea":{
"$addToSet":{"Name":"$_id.functionalArea","Count":"$count"}
},
"minimumEducation":{
"$addToSet":{"Name":"$_id.minimumEducation","Count":"$count"}
},
"gender":{"$addToSet":{"Name":"$_id.gender","Count":"$count"}},"contractType":{"$addToSet":{"Name":"$_id.contractType","Count":"$count"}},"locations":{"$addToSet":{"Name":"$_id.locations","Count":"$count"}},"requiredLanguages":{"$addToSet":{"Name":"$_id.requiredLanguages","Count":"$count"}},"company":{"$addToSet":{"Name":"$_id.company","Count":"$count"}}}}]
)
my document inside collection schema is like:
/* 1 */
{
"_id" : ObjectId("59e4540bf14f1607b90ffb81"),
"vacancyNumber" : "1",
"position" : "Software Tester",
"publishDate" : ISODate("2018-01-02T00:00:00.000Z"),
"expireDate" : ISODate("2018-05-29T00:00:00.000Z"),
"yearsOfExperience" : 40,
"minimumEducation" : "Doctorate",
"functionalArea" : "Education",
"company" : {
"id" : ObjectId("59e453fbf14f1607b90ffb80"),
"name" : "First Company",
"profile" : "profile",
"logo" : {
"container" : "companyFiles",
"name" : "abbbff58cd3fda2c59ab2ee620ea5aa0",
"mime" : ".png",
"size" : 5806
}
},
"durations" : {
"years" : 3,
"months" : 4
},
"probationPeriod" : {
"duration" : 34,
"unit" : "month"
},
"salary" : {
"minSalary" : 1000,
"maxSalary" : 2000,
"currency" : "USD",
"period" : "monthly",
"isNegotiable" : true
},
"locations" : [
"Germany",
"Itly",
"Iran"
],
"canApplyOnline" : true,
"skills" : [
"Skill1",
"Skill2",
"Skill3",
"Skill4"
],
"requiredLanguages" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"keywords" : [
"Key1",
"Key2"
],
"deleted" : false,
"deletedAt" : null,
"isDrafted" : false,
"isPublished" : true,
"requiresTravel" : true,
"gender" : "male",
"nationalities" : [
"afghan"
],
"workType" : "Full Time",
"contractType" : "Permanent",
}
/* 2 */
{
"_id" : ObjectId("59f9402e05d04ebe5653d98f"),
"vacancyNumber" : "1",
"position" : "Software Engineer",
"publishDate" : ISODate("2018-01-03T00:00:00.000Z"),
"expireDate" : ISODate("2018-11-10T00:00:00.000Z"),
"yearsOfExperience" : 40,
"minimumEducation" : "Doctorate",
"functionalArea" : "Education",
"company" : {
"id" : ObjectId("59e453fbf14f1607b90ffb80"),
"name" : "First Company",
"profile" : "profile",
"logo" : {
"container" : "logo container",
"name" : "logo name",
"mime" : "logo mime type",
"size" : 1
}
},
"durations" : {
"years" : 3,
"months" : 4
},
"probationPeriod" : {
"duration" : 34,
"unit" : "month"
},
"salary" : {
"minSalary" : 1000,
"maxSalary" : 2000,
"currency" : "USD",
"period" : "monthly",
"isNegotiable" : true
},
"locations" : [
"Afghanistan",
"Itly",
"Iran"
],
"skills" : [
"Skill1",
"Another Skill"
],
"requiredLanguages" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"keywords" : [
"Keyword",
"Key1"
],
"deleted" : false,
"deletedAt" : null,
"isDrafted" : false,
"isPublished" : true,
"gender" : "male",
"nationalities" : [
"afghan",
"iranian"
],
"workType" : "Full Time",
"contractType" : "Short-Term",
}
/* 3 */
{
"_id" : ObjectId("5a03235234f7504f13970abd"),
"vacancyNumber" : "1",
"position" : "Software Tester",
"publishDate" : ISODate("2017-10-10T00:00:00.000Z"),
"expireDate" : ISODate("2018-11-25T00:00:00.000Z"),
"yearsOfExperience" : 40,
"minimumEducation" : "Doctorate",
"functionalArea" : "IT Software",
"company" : {
"id" : ObjectId("59e453fbf14f1607b90ffb80"),
"name" : "My First Company",
"profile" : "profile",
"logo" : {
"container" : "logo container",
"name" : "logo name",
"mime" : "logo mime type",
"size" : 1
}
},
"durations" : {
"years" : 3,
"months" : 4
},
"probationPeriod" : {
"duration" : 34,
"unit" : "month"
},
"salary" : {
"minSalary" : 1000,
"maxSalary" : 2000,
"currency" : "USD",
"period" : "monthly",
"isNegotiable" : true
},
"locations" : [
"Germany",
"Itly",
"Iran"
],
"skills" : [
"Skill1",
"Test Skill"
],
"requiredLanguages" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"keywords" : [
"Test Key",
"Keyword"
],
"deleted" : false,
"deletedAt" : null,
"isDrafted" : false,
"isPublished" : true,
"gender" : "female",
"nationalities" : [
"afghan"
],
"workType" : "Part Time",
"contractType" : "Permanent",
}
Now I want to count the group of data by my custom expression check 'twentyFourHourAgo, fortyEightHourAgo, thirtyDaysAgo', and also by the value of a field (functionalArea, position, locations, keywords, workType).
My current query result is
{
"_id" : null,
"twentyFourHourAgo" : 0,
"fortyEightHourAgo" : 0.0,
"thirtyDaysAgo" : 2.0,
"position" : [
{
"Name" : "Software Engineer",
"Count" : 1.0
},
{
"Name" : "Software Tester",
"Count" : 1.0
}
],
"workType" : [
{
"Name" : "Full Time",
"Count" : 1.0
},
{
"Name" : "Part Time",
"Count" : 1.0
}
],
"functionalArea" : [
{
"Name" : "Education",
"Count" : 1.0
},
{
"Name" : "IT Software",
"Count" : 1.0
}
],
"minimumEducation" : [
{
"Name" : "Doctorate",
"Count" : 1.0
}
],
"gender" : [
{
"Name" : "male",
"Count" : 1.0
},
{
"Name" : "female",
"Count" : 1.0
}
],
"contractType" : [
{
"Name" : "Short-Term",
"Count" : 1.0
},
{
"Name" : "Permanent",
"Count" : 1.0
}
],
"locations" : [
{
"Name" : [
"Afghanistan",
"Itly",
"Iran"
],
"Count" : 1.0
},
{
"Name" : [
"Germany",
"Itly",
"Iran"
],
"Count" : 1.0
}
],
"requiredLanguages" : [
{
"Name" : [
"Arabic",
"English",
"Russian",
"Dari",
"French"
],
"Count" : 1.0
}
],
"company" : [
{
"Name" : "First Company",
"Count" : 1.0
},
{
"Name" : "My First Company",
"Count" : 1.0
}
]
}
As you see, I have three document that has following properties:
Two document that has the same position Software Tester, but query return 1 Software Tester (It means if I have multiple documents that have some common values in specific columns, their count result is wrong). The same problem exists for other fields 'contractType, workType, etc...'.
In array-type fields such as locations, my first document has Germany, Italy, Iran values in locations array, my second document has Afghanistan, Italy, Iran, and my third document has Germany, Italy, Iran. But query result is like this:
"locations" : [
{
"Name" : [
"Afghanistan",
"Itly",
"Iran"
],
"Count" : 1.0
},
{
"Name" : [
"Germany",
"Itly",
"Iran"
],
"Count" : 1.0
}
],
This should be like: Germany => 2, Italy,Iran => 3, and Afghanistan => 1
The same problem exists for other array type fields.
Apologies I misunderstood your question earlier. To be able to $unwind the location array, but NOT effect your twentyFourHourAgo etc you could look at using $first.
You'll need to $unwind any array if you wish count/sum the individual elements.
Example of how using $first.
db.getCollection('foo').aggregate([
{ $unwind : "$locations" },
{ "$group" : { "_id" : "$_id",
"twentyFourHourAgo":{ $first : {
"$sum" : { "$cond":[
{"$gt":["$publishDate", ISODate("2016-10-10T00:00:00.000Z")]},1,0 ] } } },
"fortyEightHourAgo" : { $first : {
"$sum" : { "$cond" : [
{ "$gt" : [ "$publishDate","2018-01-02T00:00:00.000Z"]},1,0 ] } } },
"thirtyDaysAgo" : { $first : {
"$sum" : { "$cond" : [
{ "$gt" : [ "$publishDate","2017-12-31T08:48:16.892Z"]},1,0 ] } } },
} },
{ "$group" : { "_id" : null,
"twentyFourHourAgo" : { "$sum" : "$twentyFourHourAgo" },
"fortyEightHourAgo" : { "$sum" : "$fortyEightHourAgo" },
"thirtyDaysAgo" : { "$sum" : "$thirtyDaysAgo" },
}}
])
Output:
"_id" : null,
"twentyFourHourAgo" : 0,
"fortyEightHourAgo" : 3.0,
"thirtyDaysAgo" : 3.0,
Please see here $first for further information on why I think it might be of use. I've stuck an $unwind at the beginning to help prove that it will solve the problem in your OP.

Need Help Join Collection

Collection Inventory sample data:
{
"_id" : "89011704252315531324",
"sku" : "A2015-01-000",
"type" : "package",
"status" : "active",
"lng" : "-72.789153",
"lat" : "44.173515",
"acq" : "28",
"gtime" : ISODate("2017-01-11T22:27:48.000Z"),
"qlng" : "-72.796501",
"qlat" : "44.214783",
"qtime" : ISODate("2016-11-27T18:21:10.000Z"),
"timestamp" : ISODate("2017-01-12T14:43:29.000Z"),
"modified" : Date(-62135596800000),
"battery" : "60",
"wearables" : [
{
"_id" : "0009003C100228234E45",
"type" : "wearable",
"status" : "active",
"battery" : "50",
"timestamp" : ISODate("2017-01-12T11:43:33.000Z")
},
{
"_id" : "004A003F200B36634E45",
"type" : "cradle",
"status" : "active",
"battery" : "64",
"timestamp" : ISODate("2017-01-11T22:27:26.000Z")
},
{
"_id" : "11223344556600000B55",
"type" : "falldetect",
"status" : "active",
"battery" : "64",
"timestamp" : ISODate("2017-01-12T08:43:29.000Z")
}
],
"company" : "ConnectAmericaProduction",
"companies" : [],
"remoteIp" : "172.31.45.196:53864",
"subscriber" : "5783e20aa2c89f346e000006",
"ring" : "90",
"speaker" : "90",
"mic" : "55",
"version" : "4352",
"cradle" : "OFF",
"ctime" : ISODate("2017-01-11T23:13:59.000Z"),
"csqtime" : Date(-62135596800000)
}
collection calllog sample data
{
"_id" : "89011704252315531324",
"cdr" : [
{
"direction" : "Outgoing",
"duration" : 46,
"timestamp" : ISODate("2016-11-23T03:25:06.000Z"),
"number" : "",
"name" : "Call Center",
"lng" : "-71.208061",
"lat" : "42.330265",
"acq" : "",
"timezone" : {
"dstOffset" : 0.0,
"rawOffset" : 0.0,
"status" : "",
"timeZoneId" : "",
"timeZoneName" : ""
}
},
{
"direction" : "Incoming",
"duration" : 51,
"timestamp" : ISODate("2016-11-23T03:26:02.000Z"),
"number" : "",
"name" : "Call Center",
"lng" : "-71.205727",
"lat" : "42.333347",
"acq" : "",
"timezone" : {
"dstOffset" : 0.0,
"rawOffset" : 0.0,
"status" : "",
"timeZoneId" : "",
"timeZoneName" : ""
}
},
{
"direction" : "Outgoing",
"duration" : 49,
"timestamp" : ISODate("2016-11-27T18:21:04.000Z"),
"number" : "",
"name" : "Call Center",
"lng" : "-72.796501",
"lat" : "44.214783",
"acq" : "",
"timezone" : {
"dstOffset" : 0.0,
"rawOffset" : -18000.0,
"status" : "OK",
"timeZoneId" : "America/New_York",
"timeZoneName" : "Eastern Standard Time"
}
}
]
}
after run this aggrgrate function
db.calllog.aggregate([{$unwind: "$cdr"}, {$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as: "wearables" }}, { "$project": { "cdr.direction": 1, "cdr.duration": 1,"cdr.date": 1,"wearables.type": 1, "wearables.status": 1, "wearables.battery": 1} }])
Result:
{ "_id" : "89011704252315531324", "cdr" : { "direction" : "Outgoing", "duration" : 46 }, "wearables" : [ { "type" : "package", "status" : "active", "battery" : "60" } ] }
{ "_id" : "89011704252315531324", "cdr" : { "direction" : "Incoming", "duration" : 51 }, "wearables" : [ { "type" : "package", "status" : "active", "battery" : "60" } ] }
{ "_id" : "89011704252315531324", "cdr" : { "direction" : "Outgoing", "duration" : 49 }, "wearables" : [ { "type" : "package", "status" : "active", "battery" : "60" } ] }
needed help can not get query to shows wearables type such as wearable, cradle, falldetect
thank
Did you try to do wearables.wearables.type? When you call wearables.type, you are actually getting the type of the Inventory. If you need the type of the wearable that is inside the inventory. You need to put inventory.wearables.type. The initial problem is that you're calling the inventory "wearables" and making a confusion out of it.
I would do the following:
db.calllog.aggregate([{$unwind: "$cdr"},
{$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as: "inventory" }},
{$unwind: "$inventory.wearables"},
{ "$project": {
"cdr.direction": 1,
"cdr.duration": 1,
"cdr.date": 1,
"inventory.type": 1,
"inventory.status": 1,
"inventory.battery": 1,
"inventory.wearables.type":1
}}])