Querying, projecting and sorting multiple fields of documents inside a mongoDB collection - mongodb

I have a simple mongoDB collection, named usersCollection, whose generale structure is this:
[
{
"username" : "john",
"sex" : "m",
"email" : "john#gmail.com",
"courses" : [
{
"title" : "medicine",
"grade": 25,
},
{
"title" : "art",
"grade": 29,
},
{
"title" : "history",
"grade": 21,
}
]
},
{
"username" : "jane",
"sex" : "f",
"email" : "jane#gmail.com",
"courses" : [
{
"title" : "math",
"grade": 20,
},
{
"title" : "medicine",
"grade": 30,
}
]
},
{
"username" : "sarah",
"sex" : "f",
"email" : "sarah#gmail.com",
"courses" : [ ]
},
{
"username" : "josh",
"sex" : "f",
"email" : "josh#gmail.com",
"courses" : [
{
"title" : "english",
"grade": 28,
}
]
},
{
"username" : "mark",
"sex" : "m",
"email" : "mark#gmail.com",
"courses" : [
{
"title" : "history",
"grade": 30,
},
{
"title" : "medicine",
"grade": 19,
},
{
"title" : "math",
"grade": 22,
}
]
}
]
Every user is a member of usersCollection and has some general informations and a list of courses that he/she has already completed with the relative grades.
Can anyone tell me how I can query usersCollection to get a descending sorted array that contains an object for all users that have already completed a specific course? Every object of this array should contains the "name", the "email" and the "grade" of the relative user.
For example, launching a query on usersCollection around the course with name "medicine", I would obtain this array:
[
{
"username": "jane",
"email": "jane#gmail.com",
"grade": 30
},
{
"username": "john",
"email": "john#gmail.com",
"grade": 25
},
{
"username": "mark",
"email": "mark#gmail.com",
"grade": 19
}
]

You can manage to do it using sort and group pipeline of mongoDB.
if you want to get any specific courses you can apply match pipeline before sort pipeline.
db.users.aggregate([
{
$unwind: "$courses"
},
{
$match: {
'courses.title': 'medicine'
}
},
{
$sort: {
'courses.title': -1,
'courses.grade': -1,
}
},
{
$group: {
_id: "$courses.title",
records: {
$push: {
"_id" : "$_id",
"username" : "$username",
"sex" : "$sex",
"email" : "$email",
"grade":"$courses.grade"
}
}
}
}
])

Related

How to query embedded array of objects based on conditions in mongodb

I have an array of objects embedded in a document and there are multiple such documents in an collection.
How to do I query those embedded array of objects with below conditions(based on the documents I have below).
First get objects whose "status" is "active"(status will not be in all the objects but only few)
Then get the "parent_user_id" of the above satisfied object and match it with the rest of the objects "parent_user_id" and get those objects
the result of the above conditions have to set instead of the original Array (i.e: "users") of objects in the output instead of all the objects present.
So if you take a look at the result am expecting there are 3 elements missing from the user array because those elements did not satisfy the above conditions.
Document I have in collection(there will be multiple document as such)
{
"_id" : ObjectId("63a8808652f40e1d48a3d1d7"),
"name" : "A",
"description" : null,
"users" : [
{
"id" : "63a8808c52f40e1d48a3d1da",
"owner" : "John Doe",
"purchase_date" : "2022-12-25,
"status" : "active",
"parent_user_id" : "63a8808c52f40e1d48a3d1da",
"recent_items": ["tomato",onion]
},
{
"id" : "63a880a552f40e1d48a3d1dc",
"owner" : "John Doe 1",
"purchase_date" : "2022-12-25,
"parent_user_id" : "63a8808c52f40e1d48a3d1da",
"recent_items": ["onion"]
},
{
"id" : "63a880f752f40e1d48assddd"
"owner" : "John Doe 2",
"purchase_date" : "2022-12-25,
"parent_user_id" : "63a8808c52f40e1d48a3d1da",
},
{
"id" : "63a880f752f40e1d48a3d207"
"owner" : "John Doe 11",
"dt" : "2022-12-25,
"status" : "inactive",
"parent_user_id" : "63a880f752f40e1d48a3d207",
},
{
"id" : "63a880f752f40e1d48agfmmb"
"owner" : "John Doe 112",
"dt" : "2022-12-25,
"status" : "active",
"parent_user_id" : "63a880f752f40e1d48agfmmb",
"recent_items": ["tomato"]
}
{
"id" : "63a880f752f40e1d48agggg"
"owner" : "John SS",
"dt" : "2022-12-25,
"status" : "inactive",
"parent_user_id" : "63a880f752f40e1d48agggg",
}
{
"id" : "63a880f752f40e1d487777"
"owner" : "John SS",
"dt" : "2022-12-25,
"parent_user_id" : "63a880f752f40e1d48agggg",
}
]
}
Result am expecting
{
"_id" : ObjectId("63a8808652f40e1d48a3d1d7"),
"name" : "A",
"description" : null,
"users" : [
{
"id" : "63a8808c52f40e1d48a3d1da",
"owner" : "John Doe",
"purchase_date" : "2022-12-25,
"status" : "active",
"parent_user_id" : "63a8808c52f40e1d48a3d1da",
"recent_items": ["tomato",onion]
},
{
"id" : "63a880a552f40e1d48a3d1dc",
"owner" : "John Doe 1",
"purchase_date" : "2022-12-25,
"parent_user_id" : "63a8808c52f40e1d48a3d1da",
},
{
"id" : "63a880f752f40e1d48assddd"
"owner" : "John Doe 2",
"purchase_date" : "2022-12-25,
"parent_user_id" : "63a8808c52f40e1d48a3d1da",
},
{
"id" : "63a880f752f40e1d48agfmmb"
"owner" : "John Doe 112",
"dt" : "2022-12-25,
"status" : "active",
"parent_user_id" : "63a880f752f40e1d48agfmmb",
"recent_items": ["tomato"]
}
]
}
i would use some $filter stages as follows :
db.collection.aggregate([
{
$addFields: {
users_matched: {
$filter: {
input: "$users",
as: "user",
cond: {
$eq: [
"active",
"$$user.status"
],
},
},
},
},
},
{
$set: {
users: {
$filter: {
input: "$users",
as: "user",
cond: {
$in: [
"$$user.parent_user_id",
"$users_matched.id"
],
},
},
},
},
},
{
$unset: "users_matched"
}
])
You can check for yourself on mongoplayground https://mongoplayground.net/p/SrpsWb4v21x
EDIT TO ANSWER THE SECOND QUESTION:
You could fix your tomato problem as follows :
db.collection.aggregate([
{
$addFields: {
active_users: {
$filter: {
input: "$users",
as: "user",
cond: {
$eq: [
"active",
"$$user.status"
],
},
},
},
tomato_users: {
$filter: {
input: "$users",
as: "user",
cond: {
$in: [
"tomato",
{
"$ifNull": [
"$$user.recent_items",
[]
]
}
],
},
},
}
},
},
{
$set: {
users: {
$filter: {
input: "$users",
as: "user",
cond: {
$and: [
{
$in: [
"$$user.parent_user_id",
"$active_users.id"
],
},
{
$in: [
"$$user.parent_user_id",
"$tomato_users.parent_user_id"
],
}
]
},
},
},
},
},
{
$unset: [
"active_users",
"tomato_users"
]
}
])
See on mongoplayground https://mongoplayground.net/p/mb21UT475yt

Mongodb how to reduce the array within the matching key and calculate avg

{
"_id" : {
"state" : "NY",
"st" : "value"
},
"List" : [
{
"id" : "21",
"score" : 18.75,
"name" : "PU"
},
{
"id" : "21",
"score" : 25.0,
"name" : "PU"
},
{
"id" : "23",
"score" : 25.0,
"name" : "CL"
},
{
"id" : "23",
"score" : 56.25,
"name" : "CL"
}
]
}
Desired result:
Match the key with id within the array and calculate avg of score.
{
"_id" : {
"state" : "New York",
"st" : "value"
},
"List" : [
{
"id" : "21",
"score" : 21.875,
"name" : "PU"
},
{
"id" : "23",
"score" : 40.625,
"name" : "CL"
}
]
}
Thank you in advance.
Query
(returns the expected result)
unwind List
group with including the id, and find avg
fix the structure to be similar with the document you want
group back to restore the document structure (reverse the unwind)
if 2 sames ids have different name(if possible to happen)
query will make them seperated members in the array.
(alternativly it could make them same member and pack the names in an array, but that would produce different schema from the one you expect to see)
Test code here
db.collection.aggregate([
{
"$unwind": {
"path": "$List"
}
},
{
"$group": {
"_id": {
"state": "$_id.state",
"st": "$_id.st",
"id": "$List.id",
"name": "$List.name"
},
"avg": {
"$avg": "$List.score"
}
}
},
{
"$project": {
"_id": {
"state": "$_id.state",
"st": "$_id.st"
},
"List": {
"name": "$_id.name",
"id": "$_id.id",
"avg": "$avg"
}
}
},
{
"$group": {
"_id": "$_id",
"List": {
"$push": "$List"
}
}
}
])

How to select collection with id in array embed from other collection mongodb

I have two collection: photos and users. I want select list user with user_id in likes array embed from photos collection.
photos:
{
"_id" : ObjectId(""),
"title": "Title",
"likes" : [
{
"user_id" : ObjectId("")
},
{
"user_id" : ObjectId("")
}
],
}
users:
{
{
"_id" : ObjectId(""),
"name": "Name1",
"avatar": "Path1",
},
{
"_id" : ObjectId(""),
"name": "Name2",
"avatar": "Path2",
},
}
Output with paging:
{
{
"_id" : ObjectId(""),
"name": "Name1",
"avatar": "Path1",
},
{
"_id" : ObjectId(""),
"name": "Name2",
"avatar": "Path2",
},
}
I think this will help you...
db.getCollection('photos').aggregate([{ $lookup:
{
from: "users",
localField: "likes.user_id",
foreignField: "_id",
as: "likes"
}
}
])
The output is:
{
"_id" : ObjectId(""),
"title" : "Title",
"likes" : [
{
"_id" : ObjectId(""),
"name" : "Name1",
"avatar" : "Path1"
},
{
"_id" : ObjectId(""),
"name" : "Name2",
"avatar" : "Path2"
}
]
}

MongoDB Return Inner Document From Array

I am trying to fetch an element from an array in a document and only the element I don't want the entire document
I tried a different method but they all return the entire document
db.dept.find({"section.classes.CRN":"1901"}).limit(100)
db.dept.where("section.classes.CRN").eq("1901").limit(100)
json
{
"_id" : ObjectId("5d70ab0c280d6b8ebb850cc1"),
"name" : "Art Studio",
"abbr" : "ARS",
"section" : [
{
"type" : "Undergraduate Courses",
"classes" : [
{
"CRN" : "193",
"Course" : "ARS100",
"Sec" : "01",
"Title" : "Drawing I",
"Cr" : "3",
"Dates" : "8/26-12/19",
"Days" : "MR",
"Time" : "1230P-0320P",
"Loc" : "SAB 226",
"Instructor" : "Schuck",
"Attributes" : "",
"Avail" : "F"
},
{
"CRN" : "293",
"Course" : "ARS100",
"Sec" : "02",
"Title" : "Drawing I",
"Cr" : "3",
"Dates" : "8/26-12/19",
"Days" : "MR",
"Time" : "0330P-0620P",
"Loc" : "SAB 226",
"Instructor" : "Itty",
"Attributes" : "",
"Avail" : "F"
},
{...
I am trying to get this or something similar when searching for a set of CRN values
json
[ {
"CRN" : "193",
"Course" : "ARS100",
"Sec" : "01",
"Title" : "Drawing I",
"Cr" : "3",
"Dates" : "8/26-12/19",
...
"Instructor" : "Schuck",
"Attributes" : "",
"Avail" : "F"
}
]
Try using the aggregate pipeline to project double nested array as:
Input:
[
{
"_id": ObjectId("5d70ab0c280d6b8ebb850cc1"),
"name": "Art Studio",
"abbr": "ARS",
"section": [
{
"type": "Undergraduate Courses",
"classes": [
{
"CRN": "193",
"Course": "ARS100",
"Sec": "01",
"Title": "Drawing I",
"Cr": "3",
"Dates": "8/26-12/19",
"Days": "MR",
"Time": "1230P-0320P",
"Loc": "SAB 226",
"Instructor": "Schuck",
"Attributes": "",
"Avail": "F"
},
{
"CRN": "293",
"Course": "ARS100",
"Sec": "02",
"Title": "Drawing I",
"Cr": "3",
"Dates": "8/26-12/19",
"Days": "MR",
"Time": "0330P-0620P",
"Loc": "SAB 226",
"Instructor": "Itty",
"Attributes": "",
"Avail": "F"
}
]
}
]
}
]
Query:
hereafter unwinding section you can filter classes for CRN
db.collection.aggregate([
{
$unwind: "$section"
},
{
$project: {
name: 1,
abbr: 1,
"section.type": 1,
"section.classes": {
$filter: {
input: "$section.classes",
as: "item",
cond: {
$eq: [
"$$item.CRN",
"193"
]
}
}
}
}
},
{
$group: {
_id: "$_id",
section: {
$push: "$section"
}
}
}
])
Output:
you can manage your keys as you want in project for adding new keys or replacing them.
[
{
"_id": ObjectId("5d70ab0c280d6b8ebb850cc1"),
"section": [
{
"classes": [
{
"Attributes": "",
"Avail": "F",
"CRN": "193",
"Course": "ARS100",
"Cr": "3",
"Dates": "8/26-12/19",
"Days": "MR",
"Instructor": "Schuck",
"Loc": "SAB 226",
"Sec": "01",
"Time": "1230P-0320P",
"Title": "Drawing I"
}
],
"type": "Undergraduate Courses"
}
]
}
]
db.dept.find({"section.classes.CRN":"1901"},{"section.classes":1}).limit(100)
It's called projection in mongodb, you pass a second object in find query to specify which fields you want in result.
so according to your above case if you want name, and section in result you should pass something like this
db.dept.find({"section.classes.CRN":"1901"},{"name":1, "section":1}).limit(100)

How sort according to given order and calculation 1st document with second one in MongoDB?

I want to get which members not present when state change and which member is present.
My given array for state order like:
[{order:1,text:'CS'}, {order:2,text:'IP'}, {order:3,text:'AC'}]
so I want to sort according to this array want to perform some operation with each pare of documents
My documents like:
{
"count" : 2,
"state" : "CS",
"members" : [
{
"email" : "builuu1998#gmail.com",
"date" : ISODate("2016-12-24T03:39:05.720Z")
},
{
"email" : "bactv.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
}
]
},
{
"count" : 1,
"state" : "AC",
"members" : [
{
"email" : "builuu1998#gmail.com",
"date" : ISODate("2016-12-24T03:39:05.720Z")
}
]
},
{
"count" : 3,
"state" : "IP",
"members" : [
{
"email" : "builuu1998#gmail.com",
"date" : ISODate("2016-12-24T03:39:05.720Z")
},
{
"email" : "bactv.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
},
{
"email" : "abc.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
}
]
}
So I want to know which members are not present from one state to another state and which members are present .
In my exam 1st state to 2nd state means (CS - IP): present 2 members and not present 1 member
{
"state": "CS_IP",
"present": [
{
"email" : "builuu1998#gmail.com",
"date" : ISODate("2016-12-24T03:39:05.720Z")
},
{
"email" : "bactv.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
}
],
"notPresent": [
{
"email" : "abc.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
}
]
}
and 2nd state to 3rd state means (IP - AC): present 1 members and not present 2 member
{"state": "IP_AC",
"present": [
{
"email" : "builuu1998#gmail.com",
"date" : ISODate("2016-12-24T03:39:05.720Z")
}
],
"notPresent": [
{
"email" : "bactv.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
},
{
"email" : "abc.hn#gmail.com",
"date" : ISODate("2016-12-25T02:32:48.698Z")
}
]}
How can I achieve this using aggregate query because I need some aggregate operation after this stage complete
You can perform one aggregation request per "couple" of state like this for ["IP", "AC"] :
db.exams.aggregate([{
$match: {
"state": {
$in: ["IP", "AC"]
}
}
}, {
"$group": {
"_id": 1,
"group1": { "$first": "$members" },
"group2": { "$last": "$members" }
}
}, {
"$project": {
"present": { "$setIntersection": ["$group1", "$group2"] },
"notPresent": {
$setUnion: [
{ "$setDifference": ["$group1", "$group2"] },
{ "$setDifference": ["$group2", "$group1"] }
]
}
}
}])
Note that this will only work for 2 elements to match (here ["IP", "AC"]) since we have to create two new fields group1 & group2 to $setIntersection and $setDifference (as there is no $group with $setIntersection and $setDifference)
The query above will give :
{
"_id": 1,
"present": [
{ "email": "builuu1998#gmail.com", "date": ISODate("2016-12-24T03:39:05.720Z") }
],
"notPresent": [
{ "email": "abc.hn#gmail.com", "date": ISODate("2016-12-25T02:32:48.698Z") },
{ "email": "bactv.hn#gmail.com", "date": ISODate("2016-12-25T02:32:48.698Z") }
]
}