aggregate multiple collections with same field mongo - node.js

I want to aggregate Collection A with Collection B and C.
Collection A's _id is saved in collection B and C as ret_id.
I tried following:
await col_A.aggregate([
{
$lookup: {
from: "col_B",
localField: "_id",
foreignField: "ret_id",
as: "task",
},
},
{
$lookup: {
from: "col_C",
localField: "_id",
foreignField: "ret_id",
as: "task",
},
},
{
$group: {
_id: "$_id",
name: { $first: "$name" },
tasks: { $push: "$task" },
},
},
])
But like that it shows nothing. I also tried to put two groups, but than I wasn't able to have the output in only one array.
So my desired output is like that:
{
_id: id,
name: name,
tasks: [
{
_id: id,
task_name: task_name
ret_id: ret_id,
// from collection B
},
{
_id: id,
task_name: task_name
ret_id: ret_id
// from collection C
},
]
}

Related

How to get the first element from a child lookup in aggregation - Mongoose

I'm trying to find all the docs from groupUserRoleSchema with a specific $match condition in the child. I'm getting the expected result, but the child application inside groupSchema is coming as an array.
I just need the first element from the application array as an object. How to convert this application into a single object.
These are my models
const groupUserRoleSchema = new mongoose.Schema({
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'group'
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}
});
const groupSchema = new mongoose.Schema({
application: {
type: mongoose.Schema.Types.ObjectId,
ref: 'application'
}
});
Here is my aggregate condition.
groupUserRoleModel.aggregate([
{
$lookup: {
from: "groups", //must be PHYSICAL collection name
localField: "group",
foreignField: "_id",
as: "group",
}
},
{
$lookup: {
from: "users",
localField: "user",
foreignField: "_id",
as: "user",
}
},
{
$lookup: {
from: "applications",
localField: "group.application",
foreignField: "_id",
as: "group.application",
}
},
{
$addFields: {
group: {
$arrayElemAt: ["$group", 0],
},
user: {
$arrayElemAt: ["$user", 0],
}
},
},
{
$match: {
"user.email_id": requestHeaders.user_email
},
}
]);
Here the $lookup group.application is coming as an array. Instead i need it as an object.
Below added is the current output screen-shot
Here is the expected output screen-shot
Any suggestions ?
A alternative is re-writing the main object return, and merge the fields.
The lookup field, gonna use the $arrayElemAt attribute at position 0, with the combination of the root element '$$ROOT'.
const result = await groupUserRoleModel.aggregate([
{
$match: {
"user.email_id": requestHeaders.user_email //The Match Query
},
},
{
$lookup: {
from: 'groups', // The collection name
localField: 'group',
foreignField: '_id',
as: 'group', // Gonna be a group
},
},
{
// Lookup returns a array, so get the first once it is a _id search
$replaceRoot: {
newRoot: {
$mergeObjects: [ // merge the object
'$$ROOT',// Get base object
{
store: {
$arrayElemAt: ['$group', 0], //Get first elemnt
},
},
],
},
},
},
]);

Combining $lookup aggregation inside updateMany?

I have a collection of users like this
[
{ _id: ObjectId("61a6d586e56ea12d6b63b68e"), fullName: "Mr A" },
{ _id: ObjectId("6231a89b009d3a86c788bf39"), fullName: "Mr B" },
{ _id: ObjectId("6231a89b009d3a86c788bf3a"), fullName: "Mr C" }
]
And a collection of complains like this
[
{ _id: ObjectId("6231aaba2a038b39d992099b"), type: "fee", postedBy: ObjectId("61a6d586e56ea12d6b63b68e" },
{ _id: ObjectId("6231aaba2a038b39d992099b"), type: "fee", postedBy: ObjectId("6231a89b009d3a86c788bf3c" },
{ _id: ObjectId("6231aaba2a038b39d992099b"), type: "fee", postedBy: ObjectId("6231a89b009d3a86c788bf3b" },
]
I want to check if the postedBy fields of complains are not existed in users, then update by using the updateMany query
By the way, I have an optional way to achieve the goal but must use 2 steps:
const complains = await Complain.aggregate()
.lookup({
from: "users",
localField: "postedBy",
foreignField: "_id",
as: "postedBy",
})
.match({
$expr: {
$eq: [{ $size: "$postedBy" }, 0],
},
});
complains.forEach(async (complain) => {
complain.type = "other";
await complain.save();
});
Therefore, can I combine 2 steps into a single updateMany query? Like $match and $lookup inside updateMany query?
With MongoDB v4.2+, you can use $merge to perform update at last stage of aggregation.
db.complains.aggregate([
{
"$lookup": {
from: "users",
localField: "postedBy",
foreignField: "_id",
as: "postedByLookup"
}
},
{
$match: {
postedByLookup: []
}
},
{
"$addFields": {
"type": "other"
}
},
{
"$project": {
postedByLookup: false
}
},
{
"$merge": {
"into": "complains",
"on": "_id",
"whenMatched": "replace"
}
}
])
Here is the Mongo playground for your reference.

Aggregate data from different collections

I am currently working on a project that has the following schema using mongoose.
User schema
const userSchema = {
name: string
email: string
medicalVisits: [{type: Schema.ObjectId, ref: "records"}]
createdAt: Date
}
Records schema
const recordSchema = {
medication: [String],
rating: Number
user: [{type: Schema.ObjectId, ref: "user"}]
tests: [{type: Schema.ObjectId, ref: "tests"}]
createdAt: Date
}
Tests schema
testScore: Number
answers: Object
user: [{type: Schema.ObjectId, ref: "user"}]
createdAt: Date
From the little schema above, I have a setup where a patient can take tests multiple times and their respective tests are saved in the Tests collection. Also, the date is recorded for all tests they take. A doctor can request to see a patient's record, in this case, the patient has only one record document that has their tests records embedded in them. Currently, I am faced with the problem of getting a patient's newest and oldest test score alongside their initial details.
I can do a mongoose populate to get all information regarding a user, e.g
await User.findById(userId).populate({
path: "medicalVisits"
model: "records"
populate: {
path: "tests"
model: "test"
}
})
And that operation returns the patient's record and all the tests they have taken since they signed up to date. But when I make such a call to the Database, I just want to retrieve the patient's newest and oldest score. In other words, I want to get the patients, Initial test score, and their most recent test score. I am new to Mongoose aggregation, I tried to use the Mongoose aggregate function, but it returns an empty array, I guess I am missing something.
Currently, this is what my aggregate pipeline looks like.
const user = await Doctor.aggregate([
{ $match: { _id: docId } },
{
$lookup: {
from: "users",
localField: "patients",
foreignField: "_id",
as: "patients",
},
},
{ $unwind: "$patients" },
{ $unwind: "$patients.medicalVisits" },
{
$lookup: {
from: "records",
localField: "patients.user",
foreignField: "_id",
as: "patientRecord",
},
},
{ $unwind: "$patientRecord" },
// { $sort: { createdAt: 1 } },
{
$group: {
_id: docId,
user: { $last: "$patients" },
record: { $last: "$patientRecord"}
},
},
]);
return user[0];
From the above snippet, my intention is:
given a doctor Id, they can see a list of their patients and also see their newest and oldest test score.
Expected Output
const output = {
userId: 6e12euido....
name: "John doe"
email: "john#john.com"
rating: 2
initialTestScore: 10
recentTestScore: 30
}
How do I go about this? Or what could be a better alternative? Thank you very much.
tried my best to understand your case, and I think your aggregation pipeline should be like:
const patientsWithNewestRecord = await Doctor.aggregate([
{ $match: { _id: docId } },
{
$lookup: {
from: "users",
localField: "patients",
foreignField: "_id",
as: "patients",
},
},
// one patient, per doc
{ $unwind: "$patients" },
// one patient with all his/her visit records, per doc
{
$lookup: {
from: "records",
localField: "patients.medicalVisits",
foreignField: "_id",
as: "patientRecords",
},
},
// one patient with one visit record, per doc
{ $unwind: "$patientRecords" },
// sort by patient first, createdAt second
{ $sort: { 'patientRecords.user': 1, 'patientRecords.createdAt': 1 } },
{
$group: {
_id: { patient: '$patientRecords.user' },
user: { $last: "$patients" },
record: { $last: "$patientRecords"}
},
},
]);
this pipeline return a list of a doctor's patients and also see their newest test record. Oldest test record should be in similar war.
Based on these collections (as I understand them from your question):
// doctor collection:
{ _id: "doc1", patients: ["user1"] }
// user collection:
{
_id: "user1", name: "John", email: "john#gmail.com",
medicalVisits: ["record1", "record2"]
}
// record collection:
{ _id: "record1", rating: 2, tests: ["test1", "test2"] }
{ _id: "record2", rating: 4, tests: ["test3"] }
// test collection:
{ _id: "test1", testScore: 12, createdAt: ISODate("2021-12-04") }
{ _id: "test2", testScore: 9, createdAt: ISODate("2021-12-05") }
{ _id: "test3", testScore: 15, createdAt: ISODate("2021-12-24") }
we can apply:
db.doctor.aggregate([
{ $match: { _id: "doc1" } }
{ $lookup: {
from: "user",
localField: "patients", foreignField: "_id",
as: "patients"
}},
{ $unwind: "$patients" }, { $unwind: "$patients.medicalVisits" },
{ $lookup: {
from: "record",
localField: "patients.medicalVisits", foreignField: "_id",
as: "records"
}},
{ $unwind: "$records" }, { $unwind: "$records.tests" },
{ $lookup: {
from: "test",
localField: "records.tests", foreignField: "_id",
as: "tests"
}},
{ $unwind: "$tests" },
{ $sort: { "tests.createdAt": 1 } },
{ $group: {
_id: "$patients._id",
name: { $first: "$patients.name" },
email: { $first: "$patients.email" },
rating: { $first: "$records.rating" },
initialTestScore: { $first: "$tests.testScore" },
recentTestScore: { $last: "$tests.testScore" }
}},
{ $set: { "userId": "$_id" } }, { $unset: "_id" }
])
in order to extract:
{
userId: "user1",
name: "John",
email: "john#gmail.com",
rating: 2,
initialTestScore: 12,
recentTestScore: 15
}
Differences compared to your query:
I $lookup the test collection as it seems you information from there to get both test dates and test scores.
I $sort by test date (createdAt) before the $group by user such that we'll be able to define the right order for selecting the $first and $last test scores.
I extract user's information by using a $first on each group on user's field (since all unwind records for a given user have the same user information): for instance email: { $first: "$patients.email" }
I extract the $first and $last test scores for a user as defined by the $sort order: initialTestScore: { $first: "$tests.testScore" } and recentTestScore: { $last: "$tests.testScore" }.
I finally $set/$unset to rename the _id field into userId
I would suggest to do the following once you have the userId / patientId:
Get their tests (all) from the database in a sorted order
Take the first and last element of the array for your initial and final test report based on the sorting order you have applied (ascending or descending)
If you can just retrieve the user details and all the tests without any sorting, then you can proceed the following way:
Run a loop through all the tests and sort the tests according to test date.
Take the first and last element of the array for your initial and final test report based on the sorting order you have applied (ascending or descending)
You will not be performing the operations on DB end, so there might be a minor speed issue, but the difference would still come out to be in milliseconds unless a user takes a billion tests.
Let me know if this helps, let me know if it doesn't

How join two collections between Objects "_id" in MongoDB

regards, I am trying to merge two collections.
Products
Categories
The point is that its only relationship is the ObjectId of the corresponding document, see:
PRODUCT COLLECTION
{
"_id": Object(607a858c2db9a42d1870270f),
"code":"CODLV001",
"name":"Product Name",
"category":"607a63e5778bf40cac75d863",
"tax":"0",
"saleValue":"0",
"status":true
}
CATEGORY COLLECTION
{
"_id": Object(607a63bf06e84e5240d377de),
"name": "Diversey Care",
"status": true
},
{
"_id": Object(607a63e5778bf40cac75d863),
"name": "Sani Tisu Profesional",
"status": true
}
WHAT I'M DOING
.collection(collection)
.aggregate([
{
$lookup: {
from: 'categories',
localField: 'products.category',
foreignField: 'categories._id',
as: 'category',
},
},
])
.toArray();
WHAT AM I GETTING?
{
_id: 607a858c2db9a42d1870270f,
code: 'CODLV001',
name: 'Product Name',
category: [ [Object], [Object] ],
tax: '0',
saleValue: '0'
}
WHAT I EXPECT?
{
_id: 607a858c2db9a42d1870270f,
code: 'CODLV001',
name: 'Product Name',
category: [ [Object] ], // or every field from category collection without an array object
tax: '0',
saleValue: '0'
}
But, if I use this way, the category field is an empty array
{
$lookup: {
from: 'categories',
localField: 'category',
foreignField: '_id',
as: 'category',
},
},
So, what i'm doing wrong (just in case I'm new in the wolrd of MongoDB)?
There are few fixes in your query,
products collection field category is string type and categories field _id is objectId type so we need to convert it to objectId using $toObjectId
$lookup, pass localField as category and pass foreignField as _id, there is no need to concat collection name
.collection(collection).aggregate([
{
$addFields: {
category: {
$toObjectId: "$category"
}
}
},
{
$lookup: {
from: "categories",
localField: "category",
foreignField: "_id",
as: "category"
}
}
]).toArray();
Playground

Facing issues in aggregation lookup. Need lookup result in same structure as defined

Schema structure
categories: [{
category: { type: Schema.Types.ObjectId, ref: 'Category' },
subCategory: [{ type: Schema.Types.ObjectId, ref: 'Category' }]
}]
Query
{
$lookup: {
from: 'categories',
localField: "categories.subCategory",
foreignField: "_id",
as: "categories.subCategory"
}
},
{
$lookup: {
from: 'categories',
localField: "categories.category",
foreignField: "_id",
as: "categories.category"
}
},
Facing issues in aggregation lookup. Need lookup result in same structure as defined.
You need to use $unwind for decoding an array, explanation is added in query comment below:
unwind your categories array
lookup for category with Category collection
unwind again because lookup will return an array and unwind will convert into object
db.collection.aggregate([
{ $unwind: "$categories" },
{
$lookup: {
from: "Category",
localField: "categories.category",
foreignField: "_id",
as: "categories.category"
}
},
{ $unwind: "$categories.category" },
lookup for subCategory with Category collection
{
$lookup: {
from: "Category",
localField: "categories.subCategory",
foreignField: "_id",
as: "categories.subCategory"
}
},
group by _id because without group lookup will multiple documents
store $$ROOT in root var, because we need to use it for replace root
push categories object that we got from lookup
{
$group: {
_id: "$_id",
root: { $mergeObjects: "$$ROOT" },
categories: { $push: "$categories" }
}
},
replace new root after merging with root and $$ROOT
{
$replaceRoot: {
newRoot: {
$mergeObjects: ["$root", "$$ROOT"]
}
}
},
remove root var because no longer needed
{
$project: { root: 0 }
}
])
For the explanation purpose i have divided in to parts, you can merge easily as all are in sequence.
Working Playground: https://mongoplayground.net/p/lKd5-MjcT1K

Resources