Find element from document - mongodb

i've passed a mysql database to mongoDB for a project. My db is about a pharmacy. I have a collection of factures, where which has the list of medicines sold. I'm trying to find the medicine which was sold the most.
{
"_id" : ObjectId("5c3c71f2760c4f47c701fe13"),
"cliente" : {
"tlmv" : "910987654",
"nome" : "Josefina Vivida da Paz",
"nif" : "122133144",
"pontos" : NumberLong(0),
"id" : NumberLong(2),
"pass" : "1eab06cab995dfeb32b6b7c709b8a6c62cabacfe",
"email" : "josefina#hotmail.pt"
},
"data_f" : ISODate("2018-06-03T00:00:01Z"),
"data_s" : ISODate("2018-06-02T23:55:59Z"),
"desconto" : 0,
"funcionario" : {
"tlmv" : "934567123",
"nome" : "Pedro Jorge Rito Lima",
"ordenado" : 800.32,
"iban" : "PT 50 2751 3262 76598707612",
"pass" : "3cfa1c281281ffe4f5db2ccfbe7a17f8a9479808",
"niss" : "14385639201",
"id" : NumberLong(2),
"cedula" : "54321"
},
"id" : NumberLong(15),
"id_c" : NumberLong(2),
"id_func" : NumberLong(2),
"medicamentos" : [
{
"categoria" : "Analg�sico",
"receita" : "N",
"des" : "Ben-U-Ron 500",
"qt" : 20,
"formato" : "granulado",
"qt_v" : NumberLong(1),
"pos" : "A12",
"lab" : "Laborat�rio do Rio Ave",
"preco_l" : 2.51,
"un" : "un",
"preco" : 2.51,
"preco_v" : 2.51,
"id" : NumberLong(1),
"stock" : NumberLong(21)
},
{
"categoria" : "Estatina",
"receita" : "S",
"des" : "Sinvastatina",
"qt" : 30,
"formato" : "comprimido",
"qt_v" : NumberLong(1),
"pos" : "K23",
"lab" : "Mylan",
"preco_l" : 16.45,
"un" : "un",
"preco" : 16.45,
"preco_v" : 16.45,
"id" : NumberLong(6),
"stock" : NumberLong(25)
}
],
"pontos_r" : NumberLong(10),
"pontos_u" : NumberLong(0),
"total" : 18.96
}
So my objective is to count every medicine -"medicamento"- sorted by different descriptions-"des". Similiar to Count on mysql. Any ideas how? The code above is abount 1 facture.

You need $unwind to get a medicine per document and then $group with $sum to get count per medicine, try:
db.collection.aggregate([
{
$unwind: "$medicamentos"
},
{
$group: {
_id: "$medicamentos.des",
count: { $sum: 1 }
}
}
])

Related

MongoDB query with multiple conditions and return first matching result

We have the below data in our collection, And only want to return/get the result that matches the first condition in the below query (First matching result without checking for other conditions). Is that possible?
Data
{
"_id" : ObjectId("638073e2ee838e2d2186624b"),
"partnerId" : ObjectId("60ad435d39f1600f7cce8f40"),
"currencyId" : ObjectId("5f7c7f2e13b5c5503cbfe64c"),
"precision" : NumberInt(3),
"version" : NumberLong(1),
"status" : "ACTIVE"
},
{
"_id" : ObjectId("638073e2ee838e2d2186624b"),
"currencyId" : ObjectId("5f7c7f2e13b5c5503cbfe64c"),
"precision" : NumberInt(3),
"version" : NumberLong(1),
"status" : "ACTIVE"
},
{
"_id" : ObjectId("637e0fdc270c9d45d487085a"),
"precision" : NumberInt(3),
"version" : NumberLong(1),
"status" : "ACTIVE"
}
Query:-
db.getCollection("INVENTORY_PARTNER_COST_PRECISION").find(
{
"$or" : [
{ "$and" : [{ "partnerId" : { "$oid" : "60ad435d39f1600f7cce8f40"}}, { "currencyId" : { "$oid" : "5f7c7f2e13b5c5503cbfe64c"}}]},
{ "$and" : [{ "partnerId" : null}, { "currencyId" : { "$oid" : "5f7c7f2e13b5c5503cbfe64c"}}]},
{ "$and" : [{ "partnerId" : null}, { "currencyId" : null}]}
]
}
)

Delete a child record from a specific parent record

I am pretty new to mongodb. I have 3 levels of documents.
Parent > Child > Child, all having _id field.
{
"_id" : "n2qw5sojs4bajrj",
"Title" : "Mr",
"Instance" : "HQ",
"FirstName" : "ppp",
"LastName" : "uuuu",
"Position" : "BF",
"EmailAddress" : "xxx#ppp.com",
"Requests" : [
{
"_id" : "121",
"Date" : "12/02/2018",
"Status" : "New",
"ApprovedBy" : {
"_id" : "sdfsdf",
"Name" : "MAN"
},
"PPE" : [
{
"_id" : "121",
"Code" : "PPE",
"Status" : "New",
"Title" : "Trousers",
"Type" : "STD",
"Size" : "10111116",
"Qty" : 1,
"LostDamage" : {
"Reason" : "asdaD",
"Location" : "Station",
"Damage" : "Damged"
}
},
{
"_id" : "122",
"Code" : "PPEOPP",
"Status" : "New",
"Title" : "TrousASDASDASDers",
"Type" : "STD",
"Size" : "10111116",
"Qty" : 1,
"LostDamage" : {
"Reason" : "asdaD",
"Location" : "Station",
"Damage" : "Damged"
}
}
]
}
]
}
I would like find out how to delete the last PPE Element (Parent > Request > PPE) by the _id column.
So I would to delete the following child:
{
"_id" : "121",
"Code" : "PPE",
"Status" : "New",
"Title" : "Trousers",
"Type" : "STD",
"Size" : "10111116",
"Qty" : 1,
"LostDamage" : {
"Reason" : "asdaD",
"Location" : "Station",
"Damage" : "Damged"
}
}
Any tips / help would be great.
Thanks
Paul
You can use MongoDb $pop to remove your last element from array. Like this go to https://docs.mongodb.com/manual/reference/operator/update/pop/
db.collection.update({id:1}, { $pop:{ 'request.PPE':1}});

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" } }
]);

Inconsistent query results with embedded documents on MongoDB

I've got a collection called payments with an example of its document shown below:
{
"_id" : ObjectId("579b5ee817e3aaac2f0aebc1"),
"updatedAt" : ISODate("2016-07-29T11:04:01.209-03:00"),
"createdAt" : ISODate("2016-07-29T10:49:28.113-03:00"),
"createdBy" : ObjectId("5763f56010cd7b03008147d4"),
"contract" : ObjectId("578cb907f1575f0300d84d09"),
"recurrence" : [
{
"when" : ISODate("2016-05-29T11:03:45.606-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2d"),
"transaction" : {
"createdAt" : ISODate("2016-05-29T11:03:45.608-03:00"),
"tid" : "9999999999999999B01A",
"status" : 4,
"code" : "00",
"message" : "Transação autorizada"
},
"status" : "PAGO"
},
{
"when" : ISODate("2016-06-29T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2c"),
"transaction" : {
"createdAt" : ISODate("2016-06-29T11:03:45.608-03:00"),
"tid" : "9999999999999999B01A",
"status" : 4,
"code" : "00",
"message" : "Transação autorizada"
},
"status" : "PAGO"
},
{
"when" : ISODate("2016-07-29T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2b"),
"status" : "ERRO",
"transaction" : {
"code" : "56",
"createdAt" : ISODate("2016-07-29T11:04:01.196-03:00"),
"message" : "Autorização negada",
"status" : 5,
"tid" : "1006993069000730B88A"
}
},
{
"when" : ISODate("2016-07-30T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e2a"),
"status" : "PENDENTE"
},
{
"when" : ISODate("2016-07-31T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e29"),
"status" : "PENDENTE"
},
{
"when" : ISODate("2016-08-01T11:03:45.608-03:00"),
"_id" : ObjectId("579b6241ea945e3631f64e28"),
"status" : "PENDENTE"
}
],
"status" : "PAGO",
"conditions" : {
"originalValue" : 7406.64,
"totalValue" : 7400,
"upfrontValue" : 1500,
"upfrontInstallments" : 3,
"balanceInstallments" : 9
},
"__v" : 0,
"transaction" : {
"code" : "00",
"createdAt" : ISODate("2016-07-29T10:49:46.610-03:00"),
"message" : "Transação autorizada",
"status" : 6,
"tid" : "1006993069000730AF5A"
}
}
If I run the query below, I get the desired document shown above:
db.payments.find({ "recurrence.transaction.tid": "1006993069000730B88A" })
However, if I run this other query, MongoDB returns my entire collection (presumably because it didn't match the subdocument's id):
db.payments.find({ "recurrence._id": ObjectId("579b6241ea945e3631f64e2b") })
Both queries should return the same result! I also checked some other questions including this one so unless I'm going crazy I'm doing the same thing. Not sure why the inconsistent results though.
Tryout this:
db.payments.find({ recurrence : { $elemMatch: { "transaction.tid": "1006993069000730B88A"} } }).pretty()

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.