Updating complete embedded document in MongoDB - mongodb

I am new to mongoDB, and I am stuck at a simple update operation:
Here is the document that I had stored:
{
"_id" : "xyz",
"basicinfo_showcase_components" : {
"display_name" : "ritesh",
"display_email" : "xyz#gmail.comxsa",
"international_phone_number" : "+91 .....",
},
"address_components" : {
"country" : "India",
"postal_code" : "500004",
"state" : "Telangana",
"city" : "Hyderabad",
"subLocality1" : "aaaa",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "addrr"
}
}
Now I want to updat the address_components in above document:
I tried:
db.portfolio.update({ "_id" : "xyz", "$isolated" : "true" },
{
"address_components" : {
"country" : "Nepal",
"postal_code" : "878799",
"state" : "Telangana",
"city" : "Kathmandu",
"subLocality1" : "xyz",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "kath..."
}
});
But after updating, the "basicinfo_showcase_components" is eliminated.
ie. the updated doc is:
{
"_id" : "ohris",
"address_components" : {
.......
}
}
Can you please point out the mistake?

In your update query you passed whole document as your update document, if you want to update just one (or more) fields of document you should use $set operator:
db.test.update({ "_id" : "xyz", "$isolated" : "true" },
{
$set : {
"address_components" : {
"country" : "Nepal",
"postal_code" : "878799",
"state" : "Telangana",
"city" : "Kathmandu",
"subLocality1" : "xyz",
"subLocality2" : "",
"subLocality3" : "",
"route" : "",
"geometry" : {
"lat" : 17.43143576387407,
"lng" : 78.464432457672046
},
"formatted_address" : "kath..."
}
}});

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

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

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

How to write mongo query for the object

{
"_id" : "WR10005",
"_class" : "com.bioraid.mes.model.WorkOrders",
"rountingNumber" : "R006",
"orderId" : "MR-1017",
"consumables" : "Chip",
"workOrderStatus" : "pending",
"deliveryStatus" : "on time",
"lastCompletedStage" : "testProces",
"dateAssigned" : ISODate("2017-02-17T05:38:57.631Z"),
"dateCompleted" : ISODate("2017-02-17T07:53:32.680Z"),
"opretorProcessStatus" : [
{
"opretorid" : "USER114",
"process" : "testProces",
"status" : "Done",
"workCenterId" : "WC1",
"startDate" : ISODate("2017-02-17T06:30:16.813Z"),
"endDate" : ISODate("2017-02-17T06:42:23.237Z"),
"qualityManagerReview" : {
"qaId" : "",
"status" : "Done",
"note" : ""
}
},
{
"opretorid" : "USER116",
"process" : "testProces",
"status" : "Done",
"workCenterId" : "WC1",
"startDate" : ISODate("2017-02-17T06:30:16.813Z"),
"endDate" : ISODate("2017-02-17T06:42:23.237Z")
}
],
"workOrdersRouting" : {
"testProces" : [
{
"routingStep" : "R006*010",
"operationName" : "Operation1",
"operationStatus" : "Completed",
"operationResult" : "Pass",
"operationNote" : "test"
},
{
"routingStep" : "R006*020",
"operationName" : "adalks",
"operationStatus" : "Completed",
"operationResult" : "Pass",
"operationNote" : "sddsdfsf"
}
],
"Embossing" : [
{
"routingStep" : "R006*030",
"operationName" : "Water Cleaning",
"operationStatus" : "",
"operationResult" : "",
"operationNote" : ""
}
],
"Turbidity" : [
{
"routingStep" : "R006*040",
"operationName" : "Embossing Assembly",
"operationStatus" : "",
"operationResult" : "",
"operationNote" : ""
}
]
}
}
I want to get {'opretorProcessStatus.qualityManagerReview.status' : {$ne : null}} but this is not giving proper result can any one help me to write this.
and other one is db.getCollection('workOrders').find({'opretorProcessStatus.qualityManagerReview.status' : "Done"}).
You can use $elemMatch to get the Document which you need.
To find documents with opretorProcessStatus.qualityManagerReview.status = Done, use this query:
db.getCollection("workOrders").find({"opretorProcessStatus":{"$elemMatch":{""qualityManagerReview.status":"Done"}}})
To find the documents which don't have status as null:
db.getCollection("workOrders").find({"opretorProcessStatus":{"$elemMatch":{""qualityManagerReview.status":{"$ne":null}}}})

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