Inserting values into an array in a nested data mongodb - mongodb

I have a data set where a documents looks like this.
{
"_id" : ObjectId("5c9873aa0fd62b0c9c84e749"),
"account_id" : "1",
"company_tree" : [
{
"id" : "5d561a07-6d2c-45ae-b249-757aa41e9b2b",
"name" : "dept12",
"privacy_advisor" : {
"name" : "wfewf",
"email" : "fwefw",
"phone" : "fwef"
},
"controller" : {
"name" : "qwqwerf",
"email" : "fwefew",
"phone" : "fwefwe"
},
"index" : 1,
"items" : [
{
"id" : "a2aae8b2-24d1-44ee-98a6-29d78835fcfd",
"name" : "dept3",
"privacy_advisor" : {
"name" : "wfewf",
"email" : "fwefw",
"phone" : "fwef"
},
"controller" : {
"name" : "qwqwerf",
"email" : "fwefew",
"phone" : "fwefwe"
},
"index" : 0,
"users" : [
{
"id" : "1",
"name" : "admin",
"email" : "admin#admin.com",
"primary_locale" : "nb",
"role_membership" : {
"id" : 1,
"active_status" : true,
"name" : "leader"
}
},
{
"id" : "f18ed780-c3c4-4a43-b1e2-f7b5deef2660",
"name" : "user",
"email" : "tromesh#tromesh.com",
"primary_locale" : "nb",
"role_membership" : {
"id" : 1,
"active_status" : true,
"name" : "user"
}
}
],
"items" : [
{
"id" : "83923ba0-8d0f-4c47-8953-0f9a86a7fcbf",
"name" : "dept4",
"privacy_advisor" : {
"name" : "wfewf",
"email" : "fwefw",
"phone" : "fwef"
},
"controller" : {
"name" : "qwqwerf",
"email" : "fwefew",
"phone" : "fwefwe"
},
"index" : 0,
"users" : [
{
"id" : "1",
"name" : "admin",
"email" : "admin#test.com",
"primary_locale" : "nb",
"role_membership" : {
"id" : 1,
"active_status" : true,
"name" : "leader"
}
},
{
"id" : "f18ed780-c3c4-4a43-b1e2-f7b5deef2660",
"name" : "user",
"email" : "tromesh#tromesh.com",
"primary_locale" : "nb",
"role_membership" : {
"id" : 2,
"active_status" : true,
"name" : "user"
}
}
],
"items" : [
{
"id" : "34bfbd43-0d48-4ccf-a1a8-27770ee9048f",
"name" : "dept5",
"privacy_advisor" : {
"name" : "wfewf",
"email" : "fwefw",
"phone" : "fwef"
},
"controller" : {
"name" : "qwqwerf",
"email" : "fwefew",
"phone" : "fwefwe"
},
"index" : 0,
"items" : [
{
"id" : "1b8f13af-ff80-46c1-ad59-df454268b4fd",
"name" : "dept6",
"privacy_advisor" : {
"name" : "wfewf",
"email" : "fwefw",
"phone" : "fwef"
},
"controller" : {
"name" : "qwqwerf",
"email" : "fwefew",
"phone" : "fwefwe"
},
"index" : 0,
"statistics" : {
"insight" : {
"value" : "88"
},
"privacyQuality" : {
"value" : "44"
}
}
}
],
"expanded" : true,
"statistics" : {
"privacyQuality" : {
"value" : "56"
}
}
}
],
"expanded" : true,
"selected" : true,
"isAccount" : true
}
],
"expanded" : true,
"statistics" : {
"insight" : {
"value" : "44"
},
"privacyQuality" : {
"value" : "89"
}
},
"isAccount" : true,
"details" : {
"company_name" : "New Company"
},
"public_id" : "e4f5ed70-3be6-11e9-b57b-ed1bd06820e4",
"internal_id" : "e4f5ed70-3be6-11e9-8fde-3df658dfaac7",
"is_public_link_published" : true,
"theme" : {
"primary" : "#3c99df",
"secondary" : "#5cc1ed",
"tertiary" : "#2176b6"
}
}
],
"expanded" : true,
"statistics" : {
"insight" : {
"value" : "75"
}
}
},
//more objects with nested properties.
];
I need to insert data to "users" array in a object in company_tree array checking the name property ("name" : "dept12"). Each object in company_tree array has nested object in "items". I already have the document _id,user data, name of department ("name" : "dept12").
This is the code that i have tried and im kind a stuck here. It would be greate if someone can guide me on hos to update this.
db.getCollection('organization').find({"_id" : ObjectId("5cdbc8d4a3a4280fe86b9085")},{"company_tree":1,'_id': false}).toArray(function (err, result) {
console.log(result);
};

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

Issue with firebase query

My query:
let query = recentRef.queryOrderedByChild(FRECENT_GROUPID).queryEqualToValue(group_id)
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
And database structure is :
And my query looks like:
(/Recent {
ep = fb343534ca520c70fe35b0a316ea8e4c;
i = groupId;
sp = fb343534ca520c70fe35b0a316ea8e4c;
})
and getting Snap (Recent) <null> when I print(snapshot).
Its strange that it was working fine but now its suddenly stopped working.
EDIT:
Complete JSON:
{
"Message" : {
"fb343534ca520c70fe35b0a316ea8e4c" : {
"-Kp0jed1EZ5BLllL5_cm" : {
"createdAt" : 1.500046597341153E9,
"groupId" : "fb343534ca520c70fe35b0a316ea8e4c",
"objectId" : "-Kp0jed1EZ5BLllL5_cl",
"senderId" : "lI6SRppSboScWo5xVjcfLL82Ogr2",
"senderName" : "Test1 Test1",
"status" : "",
"text" : "hi",
"type" : "text",
"updatedAt" : 1.50004659734136E9
}
}
},
"Recent" : {
"-Kp0jecwejhzQbbm62CW" : {
"counter" : 0,
"createdAt" : 1.500046600967624E9,
"description" : "Test1 Test1",
"groupId" : "fb343534ca520c70fe35b0a316ea8e4c",
"lastMessage" : "hi",
"members" : [ "lI6SRppSboScWo5xVjcfLL82Ogr2", "fnRvHFpaoDhXqM1se7NoTSiWZIZ2" ],
"objectId" : "-Kp0jecwejhzQbbm62CV",
"picture" : "",
"type" : "private",
"updatedAt" : 1.500046600967647E9,
"userId" : "fnRvHFpaoDhXqM1se7NoTSiWZIZ2"
},
"-Kp0jed-FU1PXt1iPr29" : {
"counter" : 0,
"createdAt" : 1.500046600971885E9,
"description" : "Srikant Root",
"groupId" : "fb343534ca520c70fe35b0a316ea8e4c",
"lastMessage" : "hi",
"members" : [ "lI6SRppSboScWo5xVjcfLL82Ogr2", "fnRvHFpaoDhXqM1se7NoTSiWZIZ2" ],
"objectId" : "-Kp0jed-FU1PXt1iPr28",
"picture" : "https://s3.amazonaws.com/top500golfdev/uploads/profile/srikant.yadav#rootinfosol.com/profilepicture.jpg",
"type" : "private",
"updatedAt" : 1.500046600971896E9,
"userId" : "lI6SRppSboScWo5xVjcfLL82Ogr2"
}
},
"User" : {
"fnRvHFpaoDhXqM1se7NoTSiWZIZ2" : {
"createdAt" : 1.500045753102713E9,
"email" : "srikant.yadav#rootinfosol.com",
"firstname" : "Srikant",
"fullname" : "Srikant Yadav",
"handle" : "Srikant",
"lastname" : "Yadav",
"networkImage" : "https://s3.amazonaws.com/top500golfdev/uploads/profile/srikant.yadav#rootinfosol.com/profilepicture.jpg",
"objectId" : "fnRvHFpaoDhXqM1se7NoTSiWZIZ2",
"online" : false,
"updatedAt" : 1.500045753102731E9
},
"lI6SRppSboScWo5xVjcfLL82Ogr2" : {
"createdAt" : 1.500045791892967E9,
"email" : "test1#gmail.com",
"firstname" : "Test1",
"fullname" : "Test1 Test1",
"handle" : "test1",
"lastname" : "Test1",
"networkImage" : "",
"objectId" : "lI6SRppSboScWo5xVjcfLL82Ogr2",
"online" : false,
"updatedAt" : 1.500046571456235E9
}
}
}

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

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

Updating complete embedded document in 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..."
}
}});