Delete a child record from a specific parent record - mongodb

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

Related

Nested object update query in mongodb

I have object in my procedures collection.
I want to update item_status of item_id 5996c80fca423ce1228f7690 which is available in preferences.items.
I want to get all records who has mentioned item_id so that we can update all occurrences.
{
"_id" : ObjectId("5996d0a1ca423ce1228f777a"),
"status" : "Active",
"procedure_name" : "ATHA",
"procedure_for" : "Admin",
"created_by" : "5940c3e8734d1d79866338cf",
"created_on" : ISODate("2017-10-19T18:44:22.702+0000"),
"speciality_id" : "5751131e3a1253845560a984",
"speciality" : "Orthopdics",
"master_template_id" : "",
"hospital_id" : "",
"surgeon_nurse_id" : "",
"procedure_type" : "Published",
"published_on" : ISODate("2017-10-19T18:44:22.702+0000"),
"surgical_sequence" : [
],
"preferences" : [
{
"category_id" : "5971fae84658f5241d8a5b70",
"category" : "Instruments",
"_id" : ObjectId("59e8f2861c999f292a837304"),
"items" : [
{
"item_id" : "5996c80fca423ce1228f7690",
"item_name" : "Battery",
"item_description" : "",
"image_name" : "BATTERY.png",
"icon_image" : "",
"side_view_image" : "",
"_id" : ObjectId("59e8f2861c999f292a837306"),
"attributes" : [
],
"subcategory" : [
{
"name" : "Power tool",
"subcategory_id" : "5996c80eca423ce1228f7549",
"parent_id" : "",
"_id" : ObjectId("5996c80fca423ce1228f7709")
},
{
"name" : "Battery",
"subcategory_id" : "5996c80eca423ce1228f750e",
"parent_id" : "5996c80eca423ce1228f7549",
"_id" : ObjectId("5996c80fca423ce1228f7708")
}
]
}
]
}
],
"__v" : NumberInt(0),
"modified_by" : "5940c3e8734d1d79866338cf",
"modified_on" : ISODate("2017-10-19T18:44:22.702+0000")
}
I'm assuming you are talking about updating status field since I don't find any field with the name item_status. If that's the case, the below query should work:
> db.procedures.updateMany({"preferences.$.items.$.item_id": "5996c80fca423ce1228f7690"}, {"$set": {"status": "new_status"}})

A query to return a single attribute of a document in mongodb

[ "_id" : ObjectId("59d1f4d0539f772aacf90f61"),
"user_id" : 1222.0,
"user_name" : "jadenn",
"email" : "jdkdkdjjjjjjjjjjjjjjjjjjjh#j.com",
"phone" : 333333333.0,
"image_ref" : "static/image/123IMG_20170917_232813.jpg",
"stories" : [
{
"title" : "accident",
"description" : "kjsbskns",
"longitude" : 19.2,
"latitude" : 81.4,
"location" : "isl",
"date" : 12.0,
"reactions" : [
{
"type" : "seen",
"date" : "1234",
"user_id" : 123.0
},
{
"type" : "seen",
"date" : "1234",
"user_id" : 123.0
}
],
"comments" : [
{
"comment" : "djksnjknfkjguye",
"date" : 123.0,
"user_id" : 123.0
},
{
"comment" : "this is the accident case ",
"date" : 123.0,
"user_id" : 123.0
}
],
"reports" : [
{
"description" : "uye",
"date" : 123.0,
"user_id" : 1232321.0
}
],
"catagory_name" : [
{
"type" : "uye"
}
]
}
]
}
Here is my document I want a query which will return only list of stories. Not a complete document of user. I searched but could not find the solution. Every solution return complete document by applying "Where condition as MYSQL"]1
You need to project on stories key from your document as below:
db.youCollection.find({}, {stories:1, _id:0})

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

Query to filter the information from a mongodb collection

I have to retrieve a list of users from list of documents which matches the condition. The document structure look like below
{
"_id" : ObjectId("660ff865d4f9075d40a1101c"),
"orderFormId" : "OF-rJw4elBYK",
"orderDetails" : [
{
"courseId" : "53fc31f443fa1fe885d3ad61",
"userInfo" : [
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "M",
"status" : "Pending Appproval",
"eMail" : "jihin345#baabte.com",
"firstName" : "Arun"
},
{
"status" : "requested",
"firstName" : "asdasd",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "asdafasd",
"userId" : "RQ-11xDPALgR",
"eMail" : "adsasd#baabte.com"
},
{
"status" : "requested",
"firstName" : "asdaf",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "fsdsdf",
"userId" : "RQ-OdoXAOLrB",
"eMail" : "ashdjasufh#baabte.com"
},
{
"status" : "requested",
"firstName" : "asdas",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "asdasd",
"userId" : "RQ-Bw2Xokmda",
"eMail" : "asdasd#gmail.com"
}
],
"userCount" : 5,
"Name" : "Compilers",
"coursePrice" : 1000,
"coursetype" : "offline"
},
{
"courseId" : "53fc31f443fa1fe885d3ad62",
"userInfo" : [
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "Raj",
"status" : "requested",
"eMail" : "jihin432#baabte.com",
"firstName" : "Nithul"
},
{
"dob" : "2015-03-22T18:30:00.000Z",
"lastName" : "P C",
"status" : "requested",
"eMail" : "jihin345#baabte.com",
"firstName" : "Kahyoom"
}
],
"userCount" : 1,
"Name" : "Computer Science 101",
"coursePrice" : 0,
"coursetype" : "offline"
},
{
"courseId" : "57fc31f443fa1fe885d3ad64",
"userInfo" : [
{
"status" : "requested",
"firstName" : "asdasd",
"dob" : "2015-03-23T18:30:00.000Z",
"lastName" : "aasdasd",
"userId" : "RQ-WqEXBkjv5",
"eMail" : "asdasd#gmail.com"
}
],
"userCount" : 1,
"coursePrice" : 0,
"Name" : "Introduction to Haptics: Self-Paced",
"coursetype" : "offline"
}
],
"companyId" : ObjectId("54128cc57525614f6e3e710a"),
"createdDate" : ISODate("2015-03-23T11:26:29.027Z"),
"updatedDate" : ISODate("2015-03-24T15:00:33.248Z"),
"crmId" : ObjectId("660ab20bd4f9075d40a10d52"),
"urmId" : ObjectId("660ab20bd4f9075d40a10d52"),
"activeFlag" : 0,
"customCompanyCode" : "baa-106",
"status" : "Pending approval"}
From above document i have to get the users who have the status "Approved" in userInfo object which exists inside this document. I have created one query but this will output all the users who have different status.My query look like below,
db.clnTrainingRequest.find({companyId:ObjectId('54128cc57525614f6e3e710a'), "orderDetails.userInfo.status":{$in:['Approved']}}).toArray()
Please any one help me to sort out this issue
You can use aggregation. You need to $unwind orderDetails and the userInfo arrays and then use the $match to get users with status Approved
db.clnTrainingRequest.aggregate(
[ { "$match": { "companyId": ObjectId('54128cc57525614f6e3e710a') },
{ "$unwind": "$orderDetails" },
{ "$unwind": "$orderDetails.userInfo" },
{ "$match": { "orderDetails.userInfo.status": "Approved" }}
]
)

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.