pull a sub document and just return it's value - mongodb

i have this cart data in mydb, cart contains array of products :
{
"_id" : ObjectId("5f3a609dfb64f953c45bc97a"),
"user_id" : ObjectId("5f3a609dfb64f953c45bc979"),
"products" : [
{
"product_id" : ObjectId("5f3a609dfb64f953c45bc97f"),
"product_name" : "Cangkir",
"product_price" : NumberLong(10000),
"productavatar" : [
"default-product.jpg"
],
"merchant_id" : ObjectId("5f3a609dfb64f953c45bc97d"),
"merchant_name" : "Merchant Test 1",
"quantity" : NumberLong(1),
"buyer_note" : "Mohon dipacking dengan rapi",
"updated" : false,
"message" : ""
}
],
"created_at" : ISODate("2020-08-17T10:49:01.692Z"),
"updated_at" : Timestamp(1597661341, 19)
}
i want pull product in cart, and just return the product is pulled.
this is my query :
//first
db.getCollection('carts').findOneAndUpdate({"_id" : ObjectId("5f3a609dfb64f953c45bc97a"), "products.product_id" :ObjectId("5f3a609dfb64f953c45bc97f")},{"$pull" : {"products" : { "product_id" : ObjectId("5f3a609dfb64f953c45bc97f")}}},{"projection" : { "products.$" : 1}})
//second
db.getCollection('carts').findOneAndUpdate({"_id" : ObjectId("5f3a609dfb64f953c45bc97a")},{"$pull" : {"products" : { "product_id" : ObjectId("5f3a609dfb64f953c45bc97f")}}},{"projection" : {"products" : {"$elemMatch" : {"product_id" : ObjectId("5f3a609dfb64f953c45bc97f")}}}})
Result
{
"_id" : ObjectId("5f3a609dfb64f953c45bc97a"),
"products" : [
{
"product_id" : ObjectId("5f3a609dfb64f953c45bc97f"),
"product_name" : "Cangkir",
"product_price" : NumberLong(10000),
"productavatar" : [
"default-product.jpg"
],
"merchant_id" : ObjectId("5f3a609dfb64f953c45bc97d"),
"merchant_name" : "Merchant Test 1",
"quantity" : NumberLong(1),
"buyer_note" : "Mohon dipacking dengan rapi",
"updated" : false,
"message" : ""
}
]
}
this query is work to pull the product but the return value is not single pulled product.
This is what i expected return :
{
"product_id" : ObjectId("5f3a609dfb64f953c45bc97f"),
"product_name" : "Cangkir",
"product_price" : NumberLong(10000),
"productavatar" : [
"default-product.jpg"
],
"merchant_id" : ObjectId("5f3a609dfb64f953c45bc97d"),
"merchant_name" : "Merchant Test 1",
"quantity" : NumberLong(1),
"buyer_note" : "Mohon dipacking dengan rapi",
"updated" : false,
"message" : ""
}
is my approach cannot be works? or i must change another approach, i have read about aggregate but i bit more confused to me
Thanks

Related

Mongoose Return One Object from Array

I use mongoose and I have this data in my mongodb :
"_id" : ObjectId("5f13e1edf7c56a896987c191"),
"deleted" : false,
"email" : "klinikkoding#gmail.com",
"firstName" : "Klinik",
"lastName" : "Koding",
"resetToken" : null,
"workspaces" : [
{
"status" : "active",
"_id" : ObjectId("5f13e124f7c56a896987c18e"),
"code" : "kk",
"name" : "Klinik Koding",
"_roleId" : ObjectId("5f13de3eb33fa33ce2a3b0dd")
},
{
"status" : "invited",
"_id" : ObjectId("5f13e13ff7c56a896987c190"),
"code" : "rm",
"name" : "The Manage",
"_roleId" : ObjectId("5f13de3eb33fa33ce2a3b0dd")
}
],
How can I return only one workspace? The output that I need is like this:
"_id" : ObjectId("5f13e1edf7c56a896987c191"),
"deleted" : false,
"email" : "klinikkoding#gmail.com",
"firstName" : "Klinik",
"lastName" : "Koding",
"resetToken" : null,
"workspaces" : [
{
"status" : "active",
"_id" : ObjectId("5f13e124f7c56a896987c18e"),
"code" : "kk",
"name" : "Klinik Koding",
"_roleId" : ObjectId("5f13de3eb33fa33ce2a3b0dd")
},
],
Anyone can help me with this query?
Try this.
async function retrieve(){
// You can retrieve it by any field. I used email because it is unique.
let data=await yourModelName.findOne({email:"klinikkoding#gmail.com"})
data.workspaces.splice(1,1)
console.log("your final result",data)
}
retrieve()

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

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

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