mongo query doesn't work with $ in field name - mongodb

Command to get raw_data:
db.raw_data.find({'cat':'like'},
{'properties':1}).limit(1).pretty()
data:
{
"_id" : ObjectId("5656b9a0c2492dec3442da52"),
"properties" : {
"subcategory" : "49",
"$carrier" : "Vodafone India",
"$radio" : "HSDPA",
"$region" : "Gujarat",
"$screen_width" : 375,
"$wifi" : false,
"mp_lib" : "iphone",
"product_unlike_flag" : false,
"mp_device_model" : "iPhone7,2",
"user_id" : "4",
"$city" : "Ahmedabad",
"$manufacturer" : "Apple",
"$os" : "iPhone OS",
"brand" : "AO",
"gender" : "Men",
"mp_country_code" : "IN",
"time" : 1445376786,
"$app_release" : "0.8.0",
"$lib_version" : "2.8.2",
"$model" : "iPhone7,2",
"$screen_height" : 667,
"category" : "48",
"$app_version" : "0.8.0",
"$os_version" : "9.0.2",
"itemcode" : "174",
"source" : "Product"
}
}
I want to extract user_id and city from this data.
I tried these Command :
Command1 :
db.raw_data.aggregate([{$group : {_id :{'user_id': "$properties.user_id","cat":"$cat","brand":"$properties.brand" } ,"num_tutorial" :{$sum:1}}} ,{ $project : {properties.$city : 1 } } ])
Command2:
db.raw_data.find({'cat':'like'},{'properties.$city':1})
which gave me an error:
Error: error: {
"$err" : "Can't canonicalize query: BadValue Positional projection 'properties.$city' does not match the query document.",
"code" : 17287
}
Is there any way/query so I can extract user-city relations from this data.

In suck cases mongodb recommends to use unicode equivalent of '$'. This method is called $ sign escaping.
So your find query will look like following:
db.raw_data.find({'cat':'like'},{'properties.\uff04city':1})
Hope this helps :)
Result:
> db.collection.find({},{'properties.\uff04city':1})
{ "_id" : ObjectId("5656e09ccb0a925b3d5d16f2"), "properties" : { "$city" : "value" } }
{ "_id" : ObjectId("5656e502cb0a925b3d5d16f3"), "properties" : { "$city" : "value" } }

Related

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

Find element from document

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

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()

Querying Embedded array fields in a document in mongodb

In mongodb databse, am having problem trying to query a field. My collection users looks like this:
{
"_id" : "sam",
"_password" : "t",
"data" : [
{
"_id" : "hp",
"nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
"edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
"options" : {
"edgeColor" : "blue",
"nodeColor" : "black"
}
},
{
"_id" : "tt",
"nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
"edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
"options" : {
"edgeColor" : "blue",
"nodeColor" : "black"
}
}
]},
{
"_id" : "bob",
"_password" : "w",
"data" : [
{
"_id" : "hello",
"nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
"edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
"options" : {
"edgeColor" : "blue",
"nodeColor" : "black"
}
},
{
"_id" : "world",
"nodeList" : [{'nodeId' : 1},{'nodeId' : 2},{'nodeId' : 3}],
"edgeList" : [{'edgeId' : 1},{'edgeId' : 2},{'edgeId' : 3}],
"options" : {
"edgeColor" : "blue",
"nodeColor" : "black"
}
}
]
}
I need to retrieve the nodeList/edgeList from this and also change the edgeColor in options given a particular _id. For eg : _ id : "bob".
I tried a few things but could not get the output.
db.users.find({ '_id': 'sam' , "users.data._id" : "hp"}, {})
db.users.findOneAndUpdate({"_id":"sam", "users.data._id": "hp"},{$addToSet:{"users.data.nodeList":{"nodeId":1,"nodeName":"Bellanduru", "lat":43.12, "long":33.43,"stock":3}}})
Please tell me what's wrong.
you declare your collection name with this db.users in selected db
and you select users collection so not necessary specify in query
for example this "users.data._id" replace with this "data._id"
replace your querys like this
db.users.find({ '_id': 'sam' , "data._id" : "hp"}, {})
db.users.findOneAndUpdate({"_id":"sam", "data._id": "hp"},{$addToSet:{"data.nodeList":{"nodeId":1,"nodeName":"Bellanduru", "lat":43.12, "long":33.43,"stock":3}}})

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.