How to query all IDs by a value from Firebase - swift

Here is my data on Firebase
{
"messages" : {
"-KFdphRHtKSovYfCRYWE" : {
"senderId" : "95cf99d8-377b-4685-a8ee-2afe69a82419",
"text" : "Chechen"
},
"-KFdpisBYxFaSrm2CO67" : {
"senderId" : "425c9449-b3f7-4d21-b57c-4134b76712dd",
"text" : "sdd"
},
"-KFdpmKXuRrzDnl_JRmF" : {
"senderId" : "425c9449-b3f7-4d21-b57c-4134b76712dd",
"text" : "c dđcv"
},
"-KFdpnSJIX48yh1KpjFo" : {
"senderId" : "95cf99d8-377b-4685-a8ee-2afe69a82419",
"text" : "Bilbo,m"
}
},
"tasks" : {
"-KEPuc8aGpYLT0-NOo50" : {
"assignee" : "Kaito Kid",
"description" : "Task1",
"endTime" : "13:58 Thursday,07/04",
"from" : "Khuong Pham",
"priority" : 1,
"progress" : 10,
"startTime" : "13:58 Tuesday,05/04"
},
"-KFbsI0Q6WB5dWc90pIR" : {
"assignee" : "Khoa Pham",
"description" : "Task2",
"endTime" : "12:38 Thursday,21/04",
"from" : "Khuong Pham",
"priority" : 2,
"progress" : 0,
"startTime" : "12:38 Wednesday,20/04"
},
"-KFdngdnHyfG2pygRx3L" : {
"assignee" : "Khoa Pham",
"description" : "Task3",
"endTime" : "21:37 Wednesday,20/04",
"from" : "Khuong Pham",
"priority" : 0,
"progress" : 10,
"startTime" : "21:37 Tuesday,19/04"
},
"-KFdo-Q8HrrPZoaQcGRj" : {
"assignee" : "Khuong Pham",
"description" : "task4",
"endTime" : "23:44 Thứ Hai,18/04",
"from" : "Khoa Pham",
"priority" : 1,
"progress" : 7,
"startTime" : "21:41 Thứ Hai,18/04"
},
"-KFdpXmuGrLOBonb976Q" : {
"assignee" : "Khoa Pham",
"description" : "Task5",
"endTime" : "21:46 Friday,22/04",
"from" : "Khuong Pham",
"priority" : 2,
"progress" : 0,
"startTime" : "21:46 Tuesday,19/04"
},
"-KFdpdnPb_BVIDQ32Ym6" : {
"assignee" : "Khuong Pham",
"description" : "task6",
"endTime" : "23:46 Thứ Hai,18/04",
"from" : "Khoa Pham",
"priority" : 1,
"progress" : 0,
"startTime" : "23:46 Thứ Hai,18/04"
}
},
"typingIndicator" : {
"95cf99d8-377b-4685-a8ee-2afe69a82419" : false
},
"users" : {
"33ab67aa-6357-4f3e-aee8-623e294c7de2" : {
"dateJoin" : "19/04/2016",
"dateOfBirth" : "01/01/1990",
"firstName" : "Binh",
"gender" : "Male",
"group" : "PHP ",
"lastName" : "Nguyen",
"phone" : "0123456789",
"position" : "PHP Developer"
},
"425c9449-b3f7-4d21-b57c-4134b76712dd" : {
"dateJoin" : "01/01/2010",
"dateOfBirth" : "03/03/1990",
"firstName" : "Khoa",
"gender" : "Male",
"group" : "iOS Team",
"lastName" : "Pham",
"phone" : "0939133994",
"position" : "Senior iOS Developer"
},
"95cf99d8-377b-4685-a8ee-2afe69a82419" : {
"dateJoin" : "20/01/2016",
"dateOfBirth" : "29/10/1993",
"firstName" : "Khuong",
"gender" : "Male",
"group" : "iOS Team",
"lastName" : "Pham",
"phone" : "01655961231",
"position" : "iOS Developer"
},
"f88a6c6f-cbc8-4d37-a7d9-4ee4c3a6fd32" : {
"dateJoin" : "13/03/2016",
"dateOfBirth" : "01/01/1993",
"firstName" : "Kaito",
"gender" : "Male",
"group" : "Android Team",
"lastName" : "Kid",
"phone" : "0939133994",
"position" : "Android Developer"
}
}
}
I want to query all IDs which has "from" key that has value "Khuong Pham".
FIREBASE_REF.childByAppendingPath("tasks").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in
print(snapshot.key) // all IDs
print(snapshot.value)
// Then Use this value to compare with "from" key has value "Khuong Pham"
// Then find the ID of it.
})
If I try this way, I have to spend more time to filter them.
Is there anyway to query faster that I can get the ID.
Any helps would be appreciated. Thanks.
UPDATE:
Here is the code:
func deleteTaskInFireBase() {
FIREBASE_REF.childByAppendingPath("tasks").queryOrderedByChild("from").observeEventType(.ChildAdded, withBlock: { snapshot in
if let from = snapshot.value["from"] as? String where (snapshot.value["from"] as? String) == "Khuong Pham" {
print("\(snapshot.key): \(from)")
}
})
}
Result is:
-KEPuc8aGpYLT0-NOo50: Khuong Pham
-KFbsI0Q6WB5dWc90pIR: Khuong Pham
-KFdngdnHyfG2pygRx3L: Khuong Pham
-KFdpXmuGrLOBonb976Q: Khuong Pham

Related

Inserting values into an array in a nested data 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);
};

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

Find records from 7 days ago from now in MongoDB

I've a collection containing objects represented like the one below:
/* 1 */
{
"_id" : ObjectId("551c6605e4c6ac495c923aab"),
"sender_id" : ObjectId("551c6605e4c6ac495c923aac"),
"rep_sender_id" : "38",
"sender_name" : "Melissa Aldridge",
"sender_title" : null,
"sender_photo_id" : "https://url/web/bundles/pdone/media/representative/photo/qlv_aldridge_melissa.jpg",
"sender_company" : "",
"recipient_id" : ObjectId("5356af6ae4c6acdc10450a23"),
"recipient_name" : "MAX GUCILATAR",
"recipient_title" : "",
"recipient_photo_id" : "webdrProfileIcon.png",
"message" : [
{
"message_link" : "20150401174059801537155",
"message_href" : "//url2/pdone/pharma_brandpage?id=20150401174059801537155&brand_id=11",
"message_href_text" : "Co-pay Card Savings Information"
}
],
"message_subject" : "has shared information about ADHD treatment option with you",
"sender_type" : "rep",
"message_type" : "share",
"supplemental" : "",
"reply_ok" : "no",
"mdate" : ISODate("2015-04-01T21:41:25.523Z"),
"date" : "Wed April 1, 2015",
"read" : "no",
"timeago" : "2015-04-01T17:41:25-04:00",
"reference_count" : 1,
"chain" : [],
"rep_header" : {
"paccode" : "PFIZER_EMAIL_SEG1",
"sync" : "",
"_st" : "ejR2NGQ0eDVrNWw1ajVqNXc0ZjN2NG4zNDQ0NDAzeDU2NDY0dTVsMjQ0YTVhMms1NjNuNDIzbDJzNG00YTU2MzU0NTNtNW0yMjQyNDIzbjJhMzA1YjNiNHQ1NTVkNGE0cDNsNHozdzIwM2o0",
"hcp_email_address" : "max.gucilatar#yahoo.com",
"email_target" : "tmb",
"inactive" : "no",
"share_date" : "4-1-2015",
"share_date_2" : ISODate("2015-04-01T09:41:25.000Z"),
"hcp_id" : "135787",
"rep_msg" : "Thank you for taking time to speak with me. Based on our discussion, I’ve attached additional materials about Quillivant XR™ (methylphenidate HCI) CII. I look forward to following up with you in the near future. Thank you.",
"session_id" : "2015040117405239775517",
"rep_id" : "38",
"hcp_fname" : "MAX",
"hcp_lname" : "GUCILATAR",
"address" : "51 OFFICE PARK DRIVE",
"city" : "JACKSONVILLE",
"zip" : "28546",
"program_path" : "https://url/web/reptool/set/",
"rep_fname" : "Melissa",
"rep_lname" : "Aldridge",
"rep_title" : null,
"rep_alias" : "Aldridge,Melissa",
"rep_photo_id" : "https://url/web/bundles/pdone/media/representative/photo/qlv_aldridge_melissa.jpg",
"email_subject" : "Melissa Aldridge has shared information about an ADHD treatment option with you.",
"mongo_id" : "5356af6ae4c6acdc10450a23"
},
"rep_shares" : [
{
"media_show_citation" : "no",
"server_path_to_media" : "https://url/web/bundles/pdone/media/qlv_veeva/brand/presentation/cost_cov-1.pdf",
"company_id" : 6,
"media_citation" : "",
"media_id" : 47,
"media_size" : "10",
"media_title" : "Co-pay%20Card%20Savings%20Information",
"media_description" : "Learn%20how%20eligible%20patients%20can%20save%20with%20the%20Quillivant%20XR%E2%84%A2%20%28methylphenidate%20HCl%29%20CII%20savings%20program.",
"media_type" : "pdf",
"media_icon" : "https://url/web/bundles/pdone/media/qlv_veeva/brand/presentation/cost_cov-1-icon.jpg",
"session_presentation_id" : "20150401174059801537155",
"media_units" : "Pages",
"brand_id" : 11,
"media_expiration_timestamp" : 457393259.2305399800000000
}
]
}
/* 2 */
{
"_id" : ObjectId("551c2b0ee4c6ac495c923a97"),
"sender_id" : ObjectId("551c2b0ee4c6ac495c923a98"),
"rep_sender_id" : "33",
"sender_name" : "Pamela Washington",
"sender_title" : null,
"sender_photo_id" : "https://url/web/bundles/pdone/media/representative/photo/Pamela_Washington.jpg",
"sender_company" : "",
"recipient_id" : ObjectId("53909cb7e4c6acaa18486fb2"),
"recipient_name" : "ALAN WEINTRAUB",
"recipient_title" : "",
"recipient_photo_id" : "webdrProfileIcon.png",
"message" : [
{
"message_link" : "201504011329211223504837",
"message_href" : "//url2/pdone/pharma_brandpage?id=201504011329211223504837&brand_id=11",
"message_href_text" : "Efficacy and Safety Information"
}
],
"message_subject" : "has shared information about ADHD treatment option with you",
"sender_type" : "rep",
"message_type" : "share",
"supplemental" : "",
"reply_ok" : "no",
"mdate" : ISODate("2015-04-01T17:29:50.718Z"),
"date" : "Wed April 1, 2015",
"read" : "no",
"timeago" : "2015-04-01T13:29:50-04:00",
"reference_count" : 1,
"chain" : [],
"rep_header" : {
"paccode" : "PFIZER_EMAIL_SEG1",
"sync" : "",
"_st" : "ejR2NGQ0eDVrNWw1ajVqNXc0ZjN2NG4zNDQ0NDAzeDU2NDY0dTVsMjQ0YTVhMms1NjNuNDIzbDJzNG00YTU2MzU0NTNtNW0yMjQyNDIzbjJhMzA1YjNiNHQ1NTVkNGE0cDNsNHozdzIwM2o0",
"hcp_email_address" : "alan.weintraub#developmentalcba.net",
"email_target" : "tmb",
"inactive" : "no",
"share_date" : "4-1-2015",
"share_date_2" : ISODate("2015-04-01T05:29:50.000Z"),
"hcp_id" : "141274",
"rep_msg" : "Thank you for taking time to speak with me. Based on our discussion, I’ve attached additional materials about Quillivant XR™ (methylphenidate HCI) CII. I look forward to following up with you in the near future. Thank you.",
"session_id" : "20150401132911346416403",
"rep_id" : "33",
"hcp_fname" : "ALAN",
"hcp_lname" : "WEINTRAUB",
"address" : "BEHAVIORAL ASSO., P.C.,STE 120",
"city" : "NORCROSS",
"zip" : "30092",
"program_path" : "https://url/web/reptool/set/",
"rep_fname" : "Pamela",
"rep_lname" : "Washington",
"rep_title" : null,
"rep_alias" : "Washington,Pamela C",
"rep_photo_id" : "https://url/web/bundles/pdone/media/representative/photo/Pamela_Washington.jpg",
"email_subject" : "Pamela Washington has shared information about an ADHD treatment option with you.",
"mongo_id" : "53909cb7e4c6acaa18486fb2"
},
"rep_shares" : [
{
"media_show_citation" : "no",
"server_path_to_media" : "https://url/web/bundles/pdone/media/qlv_veeva/brand/presentation/eff_ramp.pdf",
"company_id" : 6,
"media_citation" : "",
"media_id" : 46,
"media_size" : "10",
"media_title" : "Efficacy%20and%20Safety%20Information",
"media_description" : "An%20overview%20of%20the%20efficacy%20and%20Important%20Safety%20Information%20for%20Quillivant%20XR%E2%84%A2%20%28methylphenidate%20HCl%29%20CII%2C%20including%20clinical%20data%20that%20show%20improvement%20in%20just%2045%20minutes%2C%20with%20efficacy%20at%204%20hours%20%28primary%20endpoint%29%20that%20lasts%20to%2012%20hours%20post-dosing.",
"media_type" : "pdf",
"media_icon" : "https://url/web/bundles/pdone/media/qlv_veeva/brand/presentation/eff_ramp-icon.jpg",
"session_presentation_id" : "201504011329211223504837",
"media_units" : "Pages",
"brand_id" : 11,
"media_expiration_timestamp" : 457378161.7262100000000000
}
]
}
I need to find the records (documents) from the last 7 days based on rep_header.share_date or by rep_header.share_date_2. I'm playing with this code but doesn't work:
var lastWeek = new Date();
lastWeek.setDate(lastWeek.getDate() -7);
db.messages.find({ "rep_header.share_date_2.$date": { $gte: lastWeek}} );
Since I get no results (Fetched 0 record(s)) and as you can see the example document is from 01/04 what is wrong?
What about this:
db.messages.find({ "rep_header.share_date_2": { '$gte': lastWeek }} )

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