How to get a list of nested object only if condition match in mongodb? - mongodb

I am developing application which had company and there are 2 users reviewer & admin inside that company. Now as a super admin I want to display only Reviewer of the all company. with following information
Company Name,
Reviewer Name,
Reviewer Email
My collection is
{
"_id" : ObjectId("58830988b9c5f808fc307ec4"),
"createdat" : ISODate("2017-01-21T07:11:04.218+0000"),
"isActive" : true,
"users" : [
{
"_id" : ObjectId("58830988b9c5f808fc307ec5"),
"createdat" : ISODate("2017-01-21T07:11:04.219+0000"),
"role" : "admin",
"password" : "test",
"email" : "email3#email.com",
"name" : "test"
},
{
"name" : "test",
"email" : "email2#email.com",
"password" : "test",
"role" : "admin",
"createdat" : ISODate("2017-01-21T07:24:42.559+0000"),
"_id" : ObjectId("58830cba24ebfa04f812e544")
},
{
"name" : "test",
"email" : "email1#email.com",
"password" : "test",
"role" : "admin",
"isActive" : true,
"createdat" : ISODate("2017-01-21T07:36:37.337+0000"),
"_id" : ObjectId("58830f85d92f1808e0984306")
},
{
"name" : "reviewName 1",
"email" : "reviewName1#gmail.com",
"password" : "test",
"role" : "reviewer",
"isActive" : true,
"createdat" : ISODate("2017-01-21T07:55:39.727+0000"),
"_id" : ObjectId("588313fba001380a383e077e")
},
{
"name" : "test",
"email" : "test",
"password" : "test",
"role" : "admin",
"isActive" : true,
"createdat" : ISODate("2017-01-21T07:56:52.963+0000"),
"_id" : ObjectId("588314447bbc230c306804c1")
}
],
"companyname" : "Test Company 1",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("58830988b9c5f808fc307ec4"),
"createdat" : ISODate("2017-01-21T07:11:04.218+0000"),
"isActive" : true,
"users" : [
{
"_id" : ObjectId("58830988b9c5f808fc307ec5"),
"createdat" : ISODate("2017-01-21T07:11:04.219+0000"),
"role" : "admin",
"password" : "test",
"email" : "test4#email.com",
"name" : "test"
},
{
"name" : "test",
"email" : "test3#email.com",
"password" : "test",
"role" : "admin",
"createdat" : ISODate("2017-01-21T07:24:42.559+0000"),
"_id" : ObjectId("58830cba24ebfa04f812e544")
},
{
"name" : "test",
"email" : "test2#email.com",
"password" : "test",
"role" : "admin",
"isActive" : true,
"createdat" : ISODate("2017-01-21T07:36:37.337+0000"),
"_id" : ObjectId("58830f85d92f1808e0984306")
},
{
"name" : "reviewName 2_1",
"email" : "reviewName2_1#gmail.com",
"password" : "test",
"role" : "reviewer",
"isActive" : true,
"createdat" : ISODate("2017-01-21T07:55:39.727+0000"),
"_id" : ObjectId("588313fba001380a383e077e")
},
{
"name" : "reviewName 2_2",
"email" : "reviewName2_2#gmail.com",
"password" : "test",
"role" : "reviewer",
"isActive" : true,
"createdat" : ISODate("2017-01-21T07:56:52.963+0000"),
"_id" : ObjectId("588314447bbc230c306804c1")
}
],
"companyname" : "Test Company 2",
"__v" : NumberInt(0)
}
So I would Like to get Following Data
Company Name : Test Company 1,
Reviewer Name : reviewName 1,
Reviewr Email : reviewName1#gmail.com
Company Name : Test Company 2,
Reviewer Name : reviewName 2_1,
Reviewer Email : reviewName2_1#gmail.com
Company Name : Test Company 2,
Reviewer Name : reviewName 2_2,
Reviewer Email : reviewName2_2#gmail.com
There will be lot's of companies, so I don't want to go through with loop and use require information in array. because there will be thousands of company and each company have hundreds of reviewer and admin. So If we go through loop then it will be time consuming. I want to get this data only from collection. So I am looking for the query or condition which gives me only require information.
Can someone help me to get these data-only.

You need to use MongoDB aggregation framework for getting the data according to your requirement.
This query will return data in the desired form.
db.collection.aggregate([
{
"$unwind": "$users"
},
{
"$match": {
"users.role":"reviewer"
}
},
{
"$project": {
"_id":0,
"Company Name" : "$companyname",
"Reviewer Name" : "$users.name",
"Reviewer Email" : "$users.email"
}
}
])

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

MongoDB update collection after a while

I have the following collection:
{ "_id" : ObjectId("5b0422b086698f39b436aa42"), "_uid" : "bQVAKHg7WWgnANHFiZOleo2FUsi4", "role" : "USER", "documentType" : "CC", "documentNumber" : 123148544, "displayName" : "Carlos Perry", "email" : "CPerry#todo.com", "phoneNumber" : "+573003004545", "photoURL" : "url", "idNetwork" : "idNetwork", "blocked" : false, "blockReason" : "Malware detection", "isDisabled": false, "lastLogin" : 1526313028249 }
{ "_id" : ObjectId("5b0423494bd76b3a308c5115"), "_uid" : "bQVAKHg7WWgnANHFiZOleo2FUsi3", "role" : "USER", "documentType" : "CC", "documentNumber" : 534567878, "displayName" : "Julian Cruz", "email" : "Jcruz#algo.com", "phoneNumber" : "+573003004545", "photoURL" : "url", "idNetwork" : "idNetwork", "blocked" : false, "blockReason" : "Malware detection", "isDisabled" :false, "lastLogin" : 1526313028249 }
And i want to update the field "lastLogin" five minutes after the user is logged into the application, but don't found a way to update mongo after five minutes.
I'm using Mongoose 5.0.3 on Node JS 9.4.0 and Mongo 3.6.2

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

MongoDB : find all entries with one key

I am trying to use mongoDB on a new project.
I have this documents in my database :
{ "_id" : ObjectId("ID"), "local" : { "rank" : "null", "password" : "PASSWORD", "email" : "EMAIL" }, "__v" : 0 }
{ "_id" : ObjectId("ID"), "local" : { "rank" : "admin", "password" : "PASSWORD", "email" : "EMAIL" }, "__v" : 0 }
{ "_id" : ObjectId("ID"), "local" : { "rank" : "null", "password" : "PASSWORD", "email" : "EMAIL" }, "__v" : 0 }
I want to find all documents with a null rank.
So I test :
db.users.find({local:{rank:"null"}})
But it doesn't work.
If I test with the command :
db.users.find({"local":{ "rank" : "null", "password" : "PASSWORD", "email" : "EMAIL" }})
It works. Why it doesn't work with the first command ?
Both comparisons you are doing against document. The second one works it matches document local.
To compare specific field inside the document you have to use dot notation.
db.users.find({"local.rank":"null"}).
More about how to query embedded document. https://docs.mongodb.com/manual/core/document/#embedded-documents

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