mongoDb field count query - mongodb

I have MongoDB collection with the following format:
{
"_id" : ObjectId("5b6b112d1bbd972848b97df4"),
"Game" : [
{
"City" : "Nizhny Novgorod",
"T2N" : "Costa Rica",
"T1N" : "Switzerland",
"ST" : "Nizhny Novgorod Stadium",
"T1S" : "2",
"Date" : "6/27/2018",
"T2S" : "2"
},
{
"City" : "Kaliningrad",
"T2N" : "Serbia",
"T1N" : "Switzerland",
"ST" : "Kaliningrad Stadium",
"T1S" : "2",
"Date" : "6/22/2018",
"T2S" : "1"
},
{
"City" : "Rostov-on-Don",
"T2N" : "Brazil",
"T1N" : "Switzerland",
"ST" : "Rostov Arena",
"T1S" : "1",
"Date" : "6/17/2018",
"T2S" : "1"
},
{
"City" : "Saint Petersburg",
"T2N" : "Sweden",
"T1N" : "Switzerland",
"ST" : "Saint Petersburg Stadium",
"T1S" : "0",
"Date" : "7/3/2018",
"T2S" : "1"
}
],
"team" : "Switzerland"
}
How can I get the total of T1S and Total of T2S for each team?
I am trying the following query
db.test3.aggregate([{$match:{}},{$group:{_id:"$team", goalScored:{$sum:"Game.T1S"},goalConceaded:{$sum:"Game.T2S"}}}])
But I am getting the following output:
{ "_id" : "Tunisia", "goalScored" : 0, "goalConceaded" : 0 }
{ "_id" : "Uruguay", "goalScored" : 0, "goalConceaded" : 0 }
{ "_id" : "Egypt", "goalScored" : 0, "goalConceaded" : 0 }
In the above, the goalscored and goalconceded are always 0 which is not expected. Any help is appreciated.

Related

How to rewrite nested object in model while update

I have a problem with update object nested in array ("companyBases"), because update scripts overwrites my nested object, i have the following model:
{
"_id" : ObjectId("5d6504541be1e64145c20c66"),
"margin" : 10,
"defaultDeprication" : 10,
"companyBases" : [
{
"_id" : ObjectId("5d6504541be1e64145c20c64"),
"name" : "Tech Parking 2",
"street" : "Traktat Ojca",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.036017,
"lat" : 20.086752
},
"__v" : 0
},
{
"_id" : ObjectId("5d6504541be1e64145c20c65"),
"name" : "Tech Parking 3",
"street" : "ul.Bieżanowska 258B",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"__v" : 0
}
],
}
I'am executing update query:
db.companies.updateOne(
{
_id: ObjectId("5d6504541be1e64145c20c66"),
"companyBases._id": ObjectId("5d6504541be1e64145c20c64")
},
{
$set: {
"companyBases.$": {
"street" : "ul.Małapolska 123"
}
}
}
)
But it overwrites my nested object and now it looking like this:
{
"_id" : ObjectId("5d6504541be1e64145c20c66"),
"margin" : 10,
"defaultDeprication" : 10,
"companyBases" : [
{
"street" : "ul.Małapolska 123"
},
{
"_id" : ObjectId("5d6504541be1e64145c20c65"),
"name" : "Tech Parking 3",
"street" : "ul.Bieżanowska 258B",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"__v" : 0
}
],
}
I would like to rewrite all field from nested object and update fields that i choose in update query.
It should looks like this (without overwriting whole object):
{
"_id" : ObjectId("5d6504541be1e64145c20c66"),
"margin" : 10,
"defaultDeprication" : 10,
"companyBases" : [
{
"_id" : ObjectId("5d6504541be1e64145c20c64"),
"name" : "Tech Parking 2",
"street" : "ul.Małapolska 123",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.036017,
"lat" : 20.086752
},
"__v" : 0
},
{
"_id" : ObjectId("5d6504541be1e64145c20c65"),
"name" : "Tech Parking 3",
"street" : "ul.Bieżanowska 258B",
"postalCode" : "30-856",
"city" : "Cracow",
"location" : {
"lng" : 50.01744,
"lat" : 20.033522
},
"__v" : 0
}
],
}
You should use arrayFilter in the update operation, as described here:
positinal filter for arrays
db.companies.updateOne(
{
_id: ObjectId("5d6504541be1e64145c20c66"),
},
{
$set: {
"companyBases.$[element].street: "ul.Małapolska 123"
}
},
{
arrayFilters: [ {"element._id": ObjectId("5d6504541be1e64145c20c64")} ]
}
)

Grouping in MongoDB Aggregate

I am starting with MongoDB and i find the Aggregate function hard to understand.
i have read many topics and tried many things, however i still don't get the results i am looking for.
I would like to group some things together to make a overview of the amount of things based on a few match parameters.
my DB:
{
"_id" : ObjectId("5943a4f015813165b6d2b79a"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "99",
"sublocation" : "02",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("5943a4f915813165b6d2b79c"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "99",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 3 */
{
"_id" : ObjectId("5943a4fe15813165b6d2b79e"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "25",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 4 */
{
"_id" : ObjectId("5943a56d15813165b6d2b7a0"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "99",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 5 */
{
"_id" : ObjectId("5943a971a367b069bb3e863c"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607274",
"location" : "98",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z"),
"__v" : 0
}
/* 6 */
{
"_id" : ObjectId("5943d824900fce1821c5845d"),
"productType" : "keychain",
"productAmount" : 1,
"orderid" : "1497607251",
"location" : "25",
"sublocation" : "01",
"date" : ISODate("2017-01-01T09:01:13.000Z")
}
/* 7 */
{
"_id" : ObjectId("5943d9ea900fce1821c5845e"),
"productType" : "mail",
"productAmount" : 1,
"orderid" : "1497607251",
"location" : "25",
"sublocation" : "02",
"date" : ISODate("2017-01-01T09:01:13.000Z")
}
my current query:
db.getCollection('products').aggregate([
{ $group: {
_id : {
"orderid" : "$orderid",
"location" : "$location",
"product" : "$productType",
"sublocation" : "$sublocation",
"date" : "$date",
"aant" : { "$sum" : "$productAmount"}
},
"aantal" : { "$sum" : 1},
"aantal2" : { "$sum" : "$productAmount"}
}
},
{
$group : {
_id : "$_id.product",
"productType" : {
"$push" : {
"loc" : "$_id.location",
"prodtype": "$_id.product",
"count": "$aantal2"},
},
"cnt": {"$sum" : "$aantal2"}
}
}
])
i would like to have this result:
{
Location: 25,
sublocation: 01,
<productTypeX> : <count the number of these products>,
<productTypeY> : <count the number of these products>,
<productTypeZ> : <count the number of these products>
},
{
Location: 25,
sublocation: 02,
<productTypeX> : <count the number of these products>,
<productTypeY> : <count the number of these products>,
<productTypeZ> : <count the number of these products>
}
or:
{
location: 25,
sublocation: 01,
products: [
{
<productTypeX> : <count>,
<productTypeY> : <count>,
<productTypeZ> : <count>
}
},
{
location: 25,
sublocation: 02
products: [
{
<productTypeX> : <count>,
<productTypeY> : <count>,
<productTypeZ> : <count>
}
}
if i get this to work i need to convert it to mongoose for NodeJS (tips are welcome)
Thanks in advance!

How to query in mongodb to get distinct record with count

I have collection who's name is transactions.
I'm sharing the object of transactions collection
{
"_id" : ObjectId("58aaec83f1dc6914082afe31"),
"amount" : "33.00",
"coordinates" : {
"lat" : "4.8168",
"lon" : "36.4909"
},
"cuisine" : "Mexican",
"date" : ISODate("0062-02-22T11:46:52.738+05:30"),
"location" : {
"address" : "2414 Trudie Rue",
"city" : "West Alisa",
"state" : "New York",
"zip" : "10000"
},
"place_name" : "Outdoors",
"place_type" : "Wooden"
},
{
"_id" : ObjectId("58aaec83f1dc6914082afe32"),
"amount" : "557.00",
"coordinates" : {
"lat" : "-36.6784",
"lon" : "131.3698"
},
"cuisine" : "Australian",
"date" : ISODate("1294-10-04T19:53:15.562+05:30"),
"location" : {
"address" : "5084 Buckridge Cove",
"city" : "Sylviaview",
"state" : "Hawaii",
"zip" : "51416-6918"
},
"place_name" : "Toys",
"place_type" : "Cotton"
},
{
"_id" : ObjectId("58aaec83f1dc6914082afe33"),
"amount" : "339.00",
"coordinates" : {
"lat" : "45.1468",
"lon" : "91.4097"
},
"cuisine" : "Mexican",
"date" : ISODate("1568-11-25T02:54:53.046+05:30"),
"location" : {
"address" : "94614 Harry Island",
"city" : "Cartwrightside",
"state" : "Louisiana",
"zip" : "18825"
},
"place_name" : "Clothing",
"place_type" : "Frozen"
},
{
"_id" : ObjectId("58aaec83f1dc6914082afe34"),
"amount" : "173.00",
"coordinates" : {
"lat" : "-57.2738",
"lon" : "19.6381"
},
"cuisine" : "Australian",
"date" : ISODate("0804-05-07T03:00:07.724+05:30"),
"location" : {
"address" : "1933 Lewis Street",
"city" : "Aufderharville",
"state" : "Louisiana",
"zip" : "23416"
},
"place_name" : "Beauty",
"place_type" : "Fresh"
},
{
"_id" : ObjectId("58aaec83f1dc6914082afe34"),
"amount" : "173.00",
"coordinates" : {
"lat" : "-57.2738",
"lon" : "19.6381"
},
"cuisine" : "Australian",
"date" : ISODate("0804-05-07T03:00:07.724+05:30"),
"location" : {
"address" : "1933 Lewis Street",
"city" : "Aufderharville",
"state" : "Louisiana",
"zip" : "23416"
},
"place_name" : "Beauty",
"place_type" : "Fresh"
}
I want to get the list of distinct cuisine with total count
Output
{
"name" : 'Mexican',
"count" : '2'
},
{
"name" : 'Australian',
"count" : '3'
},
I could have done easily with mysql but I dot know in mongodb as I'm new with mongodb
I have tried with the example and I found nothing:
db.transactions.aggregate(
{$group: {_id:'$cuisine'},count:{$sum:1}}
).result;
Please try the code below. You should group by cuisine the records and get the count of them. Later in project pipeline you can define the final look.
db.transactions.aggregate([
{ $group: { _id: "$cuisine", count: { $sum: 1 } } },
{ $project:{ _id: 0, name: "$_id", count:"$count" } }
]);

Get all array subdocuments with a conditional in MongoDB

I have a collection with lot of documents like this:
{
"Items" : [],
"Technicians" : [],
"_id" : ObjectId("537b5ea4c61b1d1743f4341f"),
"budgets" : [
{
"concepts" : [
{
"position" : 0,
"description" : "A",
"price" : "1",
"qty" : "11",
"total" : 11
},
{
"position" : 1,
"description" : "A",
"price" : "2",
"qty" : "22",
"total" : 44
},
{
"position" : 2,
"description" : "A",
"price" : "3",
"qty" : "33",
"total" : 99
},
{
"position" : 3,
"description" : "A",
"price" : "4",
"qty" : "44",
"total" : 176
}
],
"date" : "2014-05-21T10:20:48.696Z",
"id" : 9989,
"status" : "joooder",
"total" : 500
},
{
"id" : 260,
"date" : "2014-05-22T11:12:40.260Z",
"concepts" : [
{
"position" : 0,
"description" : "Nueva",
"price" : "1",
"qty" : "1",
"total" : 1
}
],
"total" : 1,
"status" : "pending"
},
{
"id" : 111,
"date" : "2014-05-22T13:36:28.111Z",
"concepts" : [
{
"position" : 0,
"description" : "Blabla",
"price" : "1",
"qty" : "11",
"total" : 11
}
],
"total" : 11,
"status" : "pending"
}
]
}
Now, I want to get the budgets, but only the budgets if status is quals to pending, but I need to find in all documents of collection.
I tried this:
db.orders.aggregate(
{ $unwind : "$budgets" },
{ $match : {
"budgets.status": "pending"
}});
But this isn't ok...
Edit two:
With this:
db.orders.aggregate(
{ $project : {
budgets : 1
}},
{ $match : {
"budgets.status": "pending"
}});
I get this:
{
"result" : [
{
"_id" : ObjectId("537b5ea4c61b1d1743f4341f"),
"budgets" : [
{
"concepts" : [
{
"position" : 0,
"description" : "A",
"price" : "1",
"qty" : "11",
"total" : 11
},
{
"position" : 1,
"description" : "A",
"price" : "2",
"qty" : "22",
"total" : 44
},
{
"position" : 2,
"description" : "A",
"price" : "3",
"qty" : "33",
"total" : 99
},
{
"position" : 3,
"description" : "A",
"price" : "4",
"qty" : "44",
"total" : 176
}
],
"date" : "2014-05-21T10:20:48.696Z",
"id" : 9989,
"status" : "joooder",
"total" : 500
},
{
"id" : 260,
"date" : "2014-05-22T11:12:40.260Z",
"concepts" : [
{
"position" : 0,
"description" : "Nueva",
"price" : "1",
"qty" : "1",
"total" : 1
}
],
"total" : 1,
"status" : "pending"
},
{
"id" : 111,
"date" : "2014-05-22T13:36:28.111Z",
"concepts" : [
{
"position" : 0,
"description" : "Blabla",
"price" : "1",
"qty" : "11",
"total" : 11
}
],
"total" : 11,
"status" : "pending"
}
]
}
],
"ok" : 1
}
The first status item isn't pending.

MongoDB : geospatial index not getting added

I have a mongo collection where each document has a 'loc' array as follows:
> db.trucks.findOne()
{
"_id" : ObjectId("52afe2a9e8de3f311ec675ee"),
"objectid" : "427856",
"fooditems" : "Cupcakes",
"facilitytype" : "Truck",
"loc" : [
37.7901490737255,
-122.398658184604
],
"priorpermit" : "0",
"location" : {
"latitude" : "37.7901490874965",
"needs_recoding" : false,
"longitude" : "-122.398658184594"
},
"lot" : "055",
"cnn" : "101000",
"status" : "REQUESTED",
"schedule" : "http://bsm.sfdpw.org/PermitsTracker/reports/report.aspx?title=schedule&report=rptSchedule&params=permit=13MFF-0068&ExportPDF=1&Filename=13MFF-0068_schedule.pdf",
"locationdescription" : "01ST ST: STEVENSON ST to JESSIE ST (21 - 56)",
"latitude" : "37.7901490737255",
"blocklot" : "3708055",
"address" : "50 01ST ST",
"received" : "Mar 14 2013 3:34PM",
"applicant" : "Cupkates Bakery, LLC",
"longitude" : "-122.398658184604",
"expirationdate" : "2013-03-15T00:00:00",
"permit" : "13MFF-0068",
"y" : "2115738.283",
"x" : "6013063.33",
"block" : "3708"
}
When I try to index on 'loc', it doesn't get added:
> db.trucks.ensureIndex( { loc : "2d" } )
> db.trucks.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "food.trucks",
"name" : "_id_"
}
]
What am I doing wrong?
Shouldn't be db.trucks.ensureIndex( { loc : "2d" } )? You are creating indexes on some other collection.