mongodb aggregate lookup with a query - mongodb

I have collections with following values:
reports
{
"_id": { "$oid": "5f05e1d13e0f6637739e215b" },
"testReport": [
{
"name": "Calcium",
"value": "87",
"slug": "ca",
"details": {
"description": "description....",
"recommendation": "recommendation....",
"isNormal": false
}
},
{
"name": "Magnesium",
"value": "-98",
"slug": "mg",
"details": {
"description": "description....",
"recommendation": "recommendation....",
"isNormal": false
}
}
],
"patientName": "Patient Name",
"clinicName": "Clinic",
"gender": "Male",
"bloodGroup": "A",
"createdAt": { "$date": "2020-07-08T15:10:09.612Z" },
"updatedAt": { "$date": "2020-07-08T15:10:09.612Z" }
},
setups
{
"_id": { "$oid": "5efcba7503f4693d164e651d" },
"code": "Ca",
"codeLower": "ca",
"name": "Calcium",
"valueFrom": -75,
"valueTo": -51,
"treatmentDescription": "description...",
"isNormal": false,
"gender": "",
"recommendation": "recommendation...",
"createdAt": { "$date": "2020-07-01T16:31:50.205Z" },
"updatedAt": { "$date": "2020-07-01T16:31:50.205Z" }
},
{
"_id": { "$oid": "5efcba7503f4693d164e651e" }, // <=== should find this for Calcium
"code": "Ca",
"codeLower": "ca",
"name": "Calcium",
"valueFrom": 76,
"valueTo": 100,
"treatmentDescription": "description...",
"isNormal": false,
"gender": "",
"recommendation": "recommendation...",
"createdAt": { "$date": "2020-07-01T16:31:50.205Z" },
"updatedAt": { "$date": "2020-07-01T16:31:50.205Z" }
},
{
"_id": { "$oid": "5efcba7603f4693d164e65bb" }, // <=== should find this for Magnesium
"code": "Mg",
"codeLower": "mg",
"name": "Magnesium",
"valueFrom": -100,
"valueTo": -76,
"treatmentDescription": "description...",
"isNormal": false,
"gender": "",
"recommendation": "recommendation...",
"createdAt": { "$date": "2020-07-01T16:31:50.205Z" },
"updatedAt": { "$date": "2020-07-01T16:31:50.205Z" }
},
{
"_id": { "$oid": "5efcba7503f4693d164e6550" },
"code": "Mg",
"codeLower": "mg",
"name": "Magnesium",
"valueFrom": 76,
"valueTo": 100,
"treatmentDescription": "description...",
"isNormal": false,
"gender": "",
"recommendation": "recommendation...",
"createdAt": { "$date": "2020-07-01T16:31:50.205Z" },
"updatedAt": { "$date": "2020-07-01T16:31:50.205Z" }
}
I want to search the value from reports collection and check whether the value is in range from the setups collection and return the _id and add the returned _ids in setupIds field on reports collection.
I tried with the following aggregation framework:
db.reports.aggegrate([
{
'$match': {
'_id': new ObjectId('5f05e1d13e0f6637739e215b')
}
}, {
'$lookup': {
'from': 'setups',
'let': {
'testValue': '$testReport.value',
'testName': '$testReport.name'
},
'pipeline': [
{
'$match': {
'$expr': {
{
'$and': [
{
'$eq': [
'$name', '$$testName'
]
}, {
'$gte': [
'$valueTo', '$$testValue'
]
}, {
'$lte': [
'$valueFrom', '$$testValue'
]
}
]
}
}
}
}
],
'as': 'setupIds'
}
}
])
This query didn't find the expected results.
This is the updated reports collection I want:
{
"_id": { "$oid": "5f05e1d13e0f6637739e215b" },
"setupIds": [{ "$oid": "5efcba7503f4693d164e651e" }, { "$oid": "5efcba7603f4693d164e65bb" }], // <=== Here, array of the ObjectId (ref: "Setups")
"patientName": "Patient Name",
"clinicName": "Clinic",
"gender": "Male",
"bloodGroup": "A",
"createdAt": { "$date": "2020-07-08T15:10:09.612Z" },
"updatedAt": { "$date": "2020-07-08T15:10:09.612Z" }
},

You can try like following
[{
$match: {
_id: ObjectId('5f05e1d13e0f6637739e215b')
}
}, {
$unwind: {
path: "$testReport"
}
}, {
$lookup: {
from: 'setup',
'let': {
testValue: {
$toInt: '$testReport.value'
},
testName: '$testReport.name'
},
pipeline: [{
$match: {
$expr: {
$and: [{
"$eq": [
"$name",
"$$testName"
]
},
{
"$gte": [
"$valueTo",
"$$testValue"
]
},
{
"$lte": [
"$valueFrom",
"$$testValue"
]
}
]
}
}
}],
as: 'setupIds'
}
}, {
$group: {
_id: "$_id",
patientName: {
$first: "$patientName"
},
clinicName: {
$first: "$clinicName"
},
gender: {
$first: "$gender"
},
bloodGroup: {
$first: "$bloodGroup"
},
createdAt: {
$first: "$createdAt"
},
updatedAt: {
$first: "$updatedAt"
},
setupIds: {
$addToSet: "$setupIds._id"
}
}
}, {
$addFields: {
setupIds: {
$reduce: {
input: "$setupIds",
initialValue: [],
in: {
$setUnion: ["$$this", "$$value"]
}
}
}
}
}]
Working Mongo playground

Related

Get a Single Object rather than and Array with One Object in MongoDB aggration

I have the following query from my Playground
Sample dataset:
[
{
"_id": {
"$oid": "637742400b359f51cb95798d"
},
"learnerId": "6377422e8a43630dcfdfd410",
"targetExam": "LON11PLUS",
"subject": "VR",
"sections": [
{
"name": "Verbal Reasoning",
"timePerSection": {
"$numberInt": "960"
},
"events": [
{
"$numberInt": "2329"
},
{
"$numberInt": "2053"
},
{
"$numberInt": "3486"
},
{
"$numberInt": "3826"
},
{
"$numberInt": "3336"
},
{
"$numberInt": "2950"
},
{
"$numberInt": "2009"
},
{
"$numberInt": "4637"
},
{
"$numberInt": "3308"
},
{
"$numberInt": "2884"
},
{
"$numberInt": "2072"
},
{
"$numberInt": "3269"
},
{
"$numberInt": "2498"
},
{
"$numberInt": "2647"
},
{
"$numberInt": "2619"
},
{
"$numberInt": "3600"
},
{
"$numberInt": "2283"
},
{
"$numberInt": "3597"
},
{
"$numberInt": "2419"
},
{
"$numberInt": "1991"
}
]
}
],
"created": "2022-11-18 08:28:48.105743",
"session": {
"id": "63778c23960b1e7e97353eea"
},
"completed": {
"$date": {
"$numberLong": "1668779074955"
}
},
"score": {
"$numberInt": "2"
}
},
{
"_id": {
"$oid": "637742590b359f51cb957990"
},
"learnerId": "6377422e8a43630dcfdfd410",
"targetExam": "LON11PLUS",
"subject": "ENG",
"sections": [
{
"name": "English",
"timePerSection": {
"$numberInt": "1500"
},
"events": [
{
"$numberInt": "779"
},
{
"$numberInt": "785"
},
{
"$numberInt": "791"
},
{
"$numberInt": "786"
},
{
"$numberInt": "784"
},
{
"$numberInt": "792"
},
{
"$numberInt": "783"
},
{
"$numberInt": "795"
},
{
"$numberInt": "781"
},
{
"$numberInt": "3041"
},
{
"$numberInt": "2053"
},
{
"$numberInt": "3497"
},
{
"$numberInt": "3840"
},
{
"$numberInt": "3023"
},
{
"$numberInt": "2285"
},
{
"$numberInt": "3022"
},
{
"$numberInt": "4644"
},
{
"$numberInt": "2477"
},
{
"$numberInt": "2472"
},
{
"$numberInt": "3338"
},
{
"$numberInt": "3270"
},
{
"$numberInt": "2018"
},
{
"$numberInt": "2288"
},
{
"$numberInt": "2260"
},
{
"$numberInt": "3603"
},
{
"$numberInt": "2463"
},
{
"$numberInt": "3600"
},
{
"$numberInt": "3312"
}
]
}
],
"created": "2022-11-18 08:29:13.804332",
"session": {
"id": "63777e1c960b1e7e97353d15"
},
"completed": {
"$date": {
"$numberLong": "1668775515232"
}
},
"score": {
"$numberInt": "6"
}
}
]
aggregate pipeline:
db.collection.aggregate([
{
$match: {
learnerId: "6377422e8a43630dcfdfd410",
targetExam: "LON11PLUS",
completed: {
$exists: true
},
},
},
{
$sort: {
completed: -1,
},
},
{
$group: {
_id: "$subject",
history: {
$push: "$$ROOT",
},
},
},
{
$group: {
_id: null,
data: {
$push: {
"k": "$_id",
"v": "$history"
},
},
},
},
{
"$replaceRoot": {
"newRoot": {
"$arrayToObject": "$data"
}
}
}
])
current output:
[
{
"ENG": [
{
"_id": ObjectId("637742590b359f51cb957990"),
"completed": ISODate("2022-11-18T12:45:15.232Z"),
"created": "2022-11-18 08:29:13.804332",
"learnerId": "6377422e8a43630dcfdfd410",
"score": 6,
"sections": [
{
"events": [
779,
785,
791,
786,
784,
792,
783,
795,
781,
3041,
2053,
3497,
3840,
3023,
2285,
3022,
4644,
2477,
2472,
3338,
3270,
2018,
2288,
2260,
3603,
2463,
3600,
3312
],
"name": "English",
"timePerSection": 1500
}
],
"session": {
"id": "63777e1c960b1e7e97353d15"
},
"subject": "ENG",
"targetExam": "LON11PLUS"
}
],
"VR": [
{
"_id": ObjectId("637742400b359f51cb95798d"),
"completed": ISODate("2022-11-18T13:44:34.955Z"),
"created": "2022-11-18 08:28:48.105743",
"learnerId": "6377422e8a43630dcfdfd410",
"score": 2,
"sections": [
{
"events": [
2329,
2053,
3486,
3826,
3336,
2950,
2009,
4637,
3308,
2884,
2072,
3269,
2498,
2647,
2619,
3600,
2283,
3597,
2419,
1991
],
"name": "Verbal Reasoning",
"timePerSection": 960
}
],
"session": {
"id": "63778c23960b1e7e97353eea"
},
"subject": "VR",
"targetExam": "LON11PLUS"
}
]
}
]
I get an array with a single object, while the way I have structured the query, there should always be a single object.
How can I get this single object as root rather than nested in an array?
If I understand the question correctly, you want the aggregate method to return a single object and not an Array that contains one object.
If that understanding is correct, then it is worth mentioning that aggregate method always returns a cursor (ref) and as a rule of thumb in MongoDB, anything that returns a cursor (find, aggregate), will always return a list a.k.a. an array.
My apologies, if you did not want to hear this, but you cannot have an aggregation returning a single object instead of an array having a single object.
Your best bet here is to just hardcode the 0'th position to get the document. Something like:
let result = await db.users.aggregate([...]);
let my_user_aggregated_data = result[0];
I hope it clarifies.

Adding Node to exisitng documents mongodb

I am trying to update the existing document with one extra field as a new requirement in DB needs that
Existing field
[{
"_id": {
"$oid": "62a8ad644035e93c7ff24607"
},
"user_name": "demo2#devia.com",
"password": "1234",
"college_id": {
"$oid": "628dfd41ef796e8f757a5c13"
},
"basic_details": {
"first_name": "ghgh",
"middle_name": "",
"last_name": "gh",
"email": "demo2#devia.com",
"mobile_number": 1234567890
},
"address_details": {
"country": {
"country_id": {
"$oid": "623012f9683f8fb7bd213c36"
},
"country_code": "IN"
},
"state": {
"state_id": {
"$oid": "623013d9683f8fb7bd2381c4"
},
"state_code": "MP"
},
"city": {
"city_id": {
"$oid": "6230139f683f8fb7bd21f1a9"
},
"city_name": "Akodia"
},
"address_line1": "",
"address_line2": "",
"pincode": ""
},
"is_verify": false,
"last_accessed": {
"$date": {
"$numberLong": "1655221604144"
}
},
"created_at": {
"$date": {
"$numberLong": "1655221604144"
}
},
"course_details": {}
}]
Needs to update all fields
[{
"_id": {
"$oid": "62bf2cf2a8c782741bbcc398"
},
"user_name": "a#exaple.com",
"password": "$2b$12$NgLNYm5jUBmFUq.w15.qCO35GiTJX09jAnOpoGuPt9G7GNuOkVN7K",
"college_id": {
"$oid": "628dfd41ef796e8f757a5c13"
},
"basic_details": {
"email": "a#example.com",
"mobile_number": "9898989898",
"first_name": "Fahim",
"middle_name": "",
"last_name": "Ashhab",
"nationality": "Antiguans",
"date_of_birth": "2003-02-04",
"admission_year": "2022-23",
"gender": "Male",
"category": "General",
"para_ability": {
"is_disable": false,
"name_of_disability": ""
}
},
"address_details": {
"communication_address": {
"country": {
"country_id": {
"$oid": "623012f9683f8fb7bd213c36"
},
"country_code": "IN"
},
"state": {
"state_id": {
"$oid": "623013d9683f8fb7bd2380ef"
},
"state_code": "AP"
},
"city": {
"city_id": {
"$oid": "6230139f683f8fb7bd21ebc8"
},
"city_name": "Akasahebpet"
},
"address_line1": "jjkjk",
"address_line2": "uiui",
"pincode": "989898"
}
},
"is_verify": true,
"last_accessed": {
"$date": {
"$numberLong": "1656696050670"
}
},
"created_at": {
"$date": {
"$numberLong": "1656696050670"
}
},
"allocate_to_counselor": {
"counselor_id": {
"$oid": "62bfd13a5ce8a398ad101bd7"
},
"counselor_name": "test",
"last_update": {
"$date": {
"$numberLong": "1656817948401"
}
}
},
"course_details": {
"BSc": {
"course_id": {
"$oid": "628e03d94e22276b98231407"
},
"course_name": "BSc",
"application_id": {
"$oid": "62bf2cf2a8c782741bbcc399"
},
"status": "Incomplete",
"specs": [
{
"spec_name": "Physician Assistant",
"is_activated": true
}
]
}
}
}]
Query Tried nothing is happening
db.collection.aggregate([
{$match:{"address_details.country": {$exists:true}}},
{$set:{address_details:{communication_address:"$address_details"}}}
])
2nd Query Tried didn't go through
db.studentsPrimaryDetails.updateMany({
"address_details.communication_address": {"$exist":false}},
{$set: {"address_details.communication_address":"$address_details"}})
The desired result needs to be
from this
"address_details": {
"country": {
"country_id": {
"$oid": "623012f9683f8fb7bd213c36"
},
"country_code": "IN"
},
"state": {
"state_id": {
"$oid": "623013d9683f8fb7bd2381c4"
},
"state_code": "MP"
},
"city": {
"city_id": {
"$oid": "6230139f683f8fb7bd21f1a9"
},
"city_name": "Akodia"
},
"address_line1": "",
"address_line2": "",
"pincode": ""
}
to this
"address_details": {
"communication_address": {
"country": {
"country_id": {
"$oid": "623012f9683f8fb7bd213c36"
},
"country_code": "IN"
},
"state": {
"state_id": {
"$oid": "623013d9683f8fb7bd2380ef"
},
"state_code": "AP"
},
"city": {
"city_id": {
"$oid": "6230139f683f8fb7bd21ebc8"
},
"city_name": "Akasahebpet"
},
"address_line1": "jjkjk",
"address_line2": "uiui",
"pincode": "989898"
}
}
Don't know what I am doing wrong.
Edit :
Desired full output
[{
"_id": {
"$oid": "62bf2cf2a8c782741bbcc398"
},
"user_name": "a#example.com",
"password": "12345678",
"college_id": {
"$oid": "628dfd41ef796e8f757a5c13"
},
"basic_details": {
"email": "a#example.com",
"mobile_number": "9898989898",
"first_name": "Fahim",
"middle_name": "",
"last_name": "Ashhab",
"nationality": "Antiguans",
"date_of_birth": "2003-02-04",
"admission_year": "2022-23",
"gender": "Male",
"category": "General",
"para_ability": {
"is_disable": false,
"name_of_disability": ""
}
},
"address_details": {
"communication_address": {
"country": {
"country_id": {
"$oid": "623012f9683f8fb7bd213c36"
},
"country_code": "IN"
},
"state": {
"state_id": {
"$oid": "623013d9683f8fb7bd2380ef"
},
"state_code": "AP"
},
"city": {
"city_id": {
"$oid": "6230139f683f8fb7bd21ebc8"
},
"city_name": "Akasahebpet"
},
"address_line1": "jjkjk",
"address_line2": "uiui",
"pincode": "989898"
}
},
"is_verify": true,
"last_accessed": {
"$date": {
"$numberLong": "1656696050670"
}
},
"created_at": {
"$date": {
"$numberLong": "1656696050670"
}
},
"allocate_to_counselor": {
"counselor_id": {
"$oid": "62bfd13a5ce8a398ad101bd7"
},
"counselor_name": "viru chaudhary",
"last_update": {
"$date": {
"$numberLong": "1656817948401"
}
}
},
"course_details": {
"BSc": {
"course_id": {
"$oid": "628e03d94e22276b98231407"
},
"course_name": "BSc",
"application_id": {
"$oid": "62bf2cf2a8c782741bbcc399"
},
"status": "Incomplete",
"specs": [
{
"spec_name": "Physician Assistant",
"is_activated": true
}
]
}
}
}]```
One option is:
Use $exists instead of $exist
Use pipeline in order to be able to $set the value from another fields' value
db.collection.updateMany(
{"address_details.communication_address": {$exists: false}},
[{$set: {address_detailsB: {communication_address: "$address_details"}}},
{$set: {
address_details: "$address_detailsB",
address_detailsB: "$$REMOVE"}
}
])
See how it works on the playground example
The aggregation query that you first tried, does not not update the db, it only returns data. In order to use it as an updater you need to add a $merge step.

Adding a nested value as a field - MongDB aggregation

So I have a parent document with users, as well as an array that has users too. I want to add the DisplayName from the nested users array to the aggregation output. Any ideas?
Output I'm looking to achieve:
[
{
"user": {
"_id": "11",
"Name": "Dave",
"DocID": "1",
"DocDisplyName": "ABC"
},
{
"user": {
"_id": "33",
"Name": "Henry",
"DocID": "1",
"DocDisplyName": "ABC",
"BranchDisplayName:"BranchA"
}
}
]
And so on.. So an array of all users and for users that belong to a branch, add the branch display Name to the output.
// Doc 1
{
"_id": "1",
"DisplayName": "ABC",
"Users": [
{ "_id": "11", "Name": "Dave" },
{ "_id": "22", "Name": "Steve" }
],
"Branches": [
{
"_id": "111",
"DisplayName": "BranchA",
"Users": [
{ "_id": "33", "Name": "Henry" },
{ "_id": "44", "Name": "Josh" },
],
},
{
"_id": "222",
"DisplayName": "BranchB",
"Users": [
{ "_id": "55", "Name": "Mark" },
{ "_id": "66", "Name": "Anton" },
],
}
]
}
``Doc 2
{
"_id": "2",
"DisplayName": "DEF",
"Users": [
{ "_id": "77", "Name": "Josh" },
{ "_id": "88", "Name": "Steve" }
],
"Branches": [
{
"_id": "333",
"DisplayName": "BranchA",
"Users": [
{ "_id": "99", "Name": "Henry" },
{ "_id": "10", "Name": "Josh" },
],
},
{
"_id": "444",
"DisplayName": "BranchB",
"Users": [
{ "_id": "112", "Name": "Susan" },
{ "_id": "112", "Name": "Mary" },
],
}
]
}
Collection.aggregate([
{
$addFields: {
branchUsers: {
$reduce: {
input: "$Branches.Users",
initialValue: [],
in: {
$concatArrays: ["$$this", "$$value"],
},
},
},
},
},
{
$addFields: {
user: {
$concatArrays: ["$branchUsers", "$Users"],
},
},
},
{
$addFields: {
"user.DocID": "$_id","user.DocDisaplyName": "$DisplayName"
},
},
{
$unwind: "$user",
},
{
$project: {
_id: 0,
user: 1,
},
}
])
Thanks in advance!
OK I found a solution.
{
$addFields: {
"branchUsers.BranchDisplayName": {
$let: {
vars: {
first: {
$arrayElemAt: [ "$Branches", 0 ]
}
},
in: "$$first.DisplayName"
}
}
}
},
This creates the field only for the users that belong to the branch

Aggregate nested arrays

I have multiple documents, and I'm trying to aggregate all documents with companyId = xxx and return one array with all the statuses.
So it will look like this:
[
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
},
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
},
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
},
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
}
]
The document look like this:
[
{
"companyId": "xxx",
"position": "",
"section": "",
"comment": "",
"items": [
{
"any": "111",
"name": "some name",
"description": "some description",
"version": "3",
"status": [
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
}
]
},
{
"any": "222",
"name": "some name",
"description": "some description",
"version": "3",
"status": [
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
}
]
}
]
},
{
"companyId": "xxx",
"position": "",
"section": "",
"comment": "",
"items": [
{
"any": "111",
"name": "some name",
"description": "some description",
"version": "3",
"status": [
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
}
]
},
{
"any": "222",
"name": "some name",
"description": "some description",
"version": "3",
"status": [
{
"status": "created",
"date": "2019-03-16T10:59:59.200Z"
},
{
"status": "completed",
"date": "2019-03-16T11:00:37.750Z"
}
]
}
]
}
]
Any suggestion, how to implement this?
Then I want to loop over the array (in code) and count how many items in status created, and completed. maybe it could be done with the query?
Thanks in advance
You can use below aggregation:
db.col.aggregate([
{
$match: { companyId: "xxx" }
},
{
$unwind: "$items"
},
{
$unwind: "$items.status"
},
{
$replaceRoot: {
newRoot: "$items.status"
}
},
{
$group: {
_id: "$status",
count: { $sum: 1 }
}
}
])
Double $unwind will return single status per document and then you can use $replaceRoot to promote each status to root level of your document.
Additionally you can add $group stage to count documents by status.
In addition to the #mickl answer, you can add $project pipeline to get the result as a flat list of status and count.
db.collectionName.aggregate([
{
$match: { companyId: "xxx" }
},
{
$unwind: "$items"
},
{
$unwind: "$items.status"
},
{
$replaceRoot: {
newRoot: "$items.status"
}
},
{
$group: {
_id: "$status",
count: { $sum: 1 }
}
},
{
$project: {
"status":"$_id",
"count":1,
_id:0
}
}
])
If the number of documents on which you are executing the above query is too much then you should avoid using $unwind in the initial stage of aggregation pipeline.
Either you should use $project after $match to reduce the selection of fields or you can use below query:
db.col.aggregate([
{
$match: {
companyId: "xxx"
}
},
{
$project: {
_id: 0,
data: {
$reduce: {
input: "$items.status",
initialValue: [
],
in: {
$concatArrays: [
"$$this",
"$$value"
]
}
}
}
}
},
{
$unwind: "$data"
},
{
$replaceRoot: {
newRoot: "$data"
}
}
])

Filter nested array in mongodb? [duplicate]

This question already has answers here:
Find in Double Nested Array MongoDB
(2 answers)
Closed 4 years ago.
I have a document that looks like so:
{
"_id": {
"$oid": "5b1586ccf0c56353e89d330b"
},
"address": {
"street": "123 Street",
"address2": "Address 2",
"city": "Some City",
"state": "MI",
"zip": "12345"
},
"subs": [
{
"invoices": [
{
"address": {
"street": "3061 Pine Ave SW",
"city": "Grandville",
"state": "AK",
"zip": "49418"
},
"lineItem": [
{
"images": [
{
"_id": {
"$oid": "5b1fca54e6ee1d80c463612d"
},
"name": "1528810066348_RSA Logo.jpeg",
"url": "https....",
"uploadDate": {
"$date": "2018-06-12T13:27:46.931Z"
},
"size": 91819
}
],
"_id": {
"$oid": "5b1fca54e6ee1d80c463612c"
},
"desc": "2",
"amt": 2
}
],
"_id": {
"$oid": "5b1fca54e6ee1d80c463612b"
}
}
],
"_id": {
"$oid": "5b1fc7f23b595481d4599f58"
},
"email": "a#a.com",
"scope": "Roof",
},
{
"invoices": [
{
"address": {
"street": "3061 Pine Ave SW",
"city": "Grandville",
"state": "AL",
"zip": "49418"
},
"lineItem": [
{
"images": [
{
"_id": {
"$oid": "5b1fca2fe6ee1d80c463612a"
},
"name": "1528810029700_RSA Stamp.png",
"url": "https....",
"uploadDate": {
"$date": "2018-06-12T13:27:10.403Z"
},
"size": 238113
}
],
"_id": {
"$oid": "5b1fca2fe6ee1d80c4636129"
},
"desc": "1",
"amt": 1
}
],
"_id": {
"$oid": "5b1fca2fe6ee1d80c4636128"
}
},
{
"address": {
"street": "3061 Pine Ave SW",
"city": "Grandville",
"state": "AL",
"zip": "49418"
},
"lineItem": [
{
"images": [
{
"_id": {
"$oid": "5b1fd05b0d1f7185e02e9c40"
},
"name": "1528811607099_error page.PNG",
"url": "https....",
"uploadDate": {
"$date": "2018-06-12T13:53:28.080Z"
},
"size": 224772
}
],
"_id": {
"$oid": "5b1fd05b0d1f7185e02e9c3f"
},
"desc": "3",
"amt": 3
}
],
"_id": {
"$oid": "5b1fd05b0d1f7185e02e9c3e"
}
}
],
"_id": {
"$oid": "5b1fc7f23b595481d4599f55"
},
"email": "b#b.com",
"scope": "Siding",
}
],
"firstName": "",
"lastName": "",
}
My issue is that I want to be able to access a specific invoices of a specific subs.
I am new to Mongo/Mongoose so it is possible I am doing something completely wrong and I would be more than happy with any answer/criticism on how I am approaching this.
-- tweaked answer --
Job.aggregate([
{
$match: {
"_id": mongoose.Types.ObjectId(req.body.jobID)
}
},
{
$unwind: "$subs"
},
{
$match: {
"subs._id": mongoose.Types.ObjectId(req.body.subID)
}
},
{
$unwind: "$subs.invoices"
},
{
$match: {
"subs.invoices._id": mongoose.Types.ObjectId(req.body.invID)
}
},
{
$project: {
"_id": 1,
"subs.invoices": 1
}
}
], function(err, job) {
if (err) throw err;
res.send(job);
});
You can try below aggregation...
Here this is a long process of deconstructing an array using $unwind and rebuild the array using $group
db.collection.aggregate([
{ "$match": { "_id": "1111" } },
{ "$unwind": "$subs" },
{ "$match": { "subs._id": "2222" } },
{ "$unwind": "$subs.invoices" },
{ "$match": { "subs.invoices._id": "3333" } },
{ "$group": {
"_id": {
"_id": "$_id",
"subs": "$subs._id"
},
"firstName": { "$first": "$firstName" },
"lastName": { "$first": "$lastName" },
"address": { "$first": "$address" },
"subs": {
"$first": {
"_id": "$subs._id",
"email": "$subs.email",
"venue": "$subs.venue",
"scope": "$subs.scope"
}
},
"invoices": { "$push": "$subs.invoices" }
}},
{ "$group": {
"_id": "$_id._id",
"firstName": { "$first": "$firstName" },
"lastName": { "$first": "$lastName" },
"address": { "$first": "$address" },
"subs": {
"$push": {
"_id": "$subs._id",
"email": "$subs.email",
"venue": "$subs.venue",
"scope": "$subs.scope",
"invoices": "$invoices"
}
}
}}
])
Or you can do this with $filter aggregation as well
db.collection.aggregate([
{ "$match": { "_id": "5b1586ccf0c56353e89d330b" }},
{ "$unwind": "$subs" },
{ "$match": { "subs._id": "5b1fc7f23b595481d4599f58" }},
{ "$project": {
"address": 1, "firstName": 1, "lastName": 1,
"subs.type": "$subs._id",
"subs.status": "$subs.email",
"subs.code": "$subs.scope",
"subs.invoices": {
"$filter": {
"input": "$subs.invoices",
"as": "invoice",
"cond": {
"$eq": [
"$$invoice._id",
"5b1fca54e6ee1d80c463612b"
]
}
}
}
}},
{ "$group": {
"_id": "$_id",
"address": { "$first": "$address" },
"firstName": { "$first": "$firstName" },
"lastName": { "$first": "$lastName" },
"subs": { "$push": "$subs" }
}}
])