Place an object to root level in mongoDb - node.js

I have a aggregate query that fetches result from 3 collections.
I am using mongoDb 3.4
One Sample doc from result.
{
"_id" : ObjectId("5ba1717ee4b00ce08ca47cfa"),
"name" : "captain jack",
"email" : "jack#gmail.com",
"mobile" : "9000000023",
"status" : "verified",
"courses" : [
{
"_id" : "13",
"name" : "Course (03)"
},{
"_id" : "12",
"name" : "Course (03)"
}
],
"examCompleted" : false,
"login" : "5ba1717ee4b00fe08ca47cfa",
"partnerMetaInfo" : {
"_id" : ObjectId("5ba1717ee4b00fe08ca47cfa"),
"costCode" : "5761",
"hub" : "CALCUTTA",
"location" : "Kolkata"
}
}
I am trying to bring partnerMetaInfo at root level.
I am also unable to filter courses._id using $match on _id == 13
This is my aggregate query :
db.getCollection("mainCollection").aggregate([
{
//Join two collection
$lookup:{
from: "Details",
localField: "username",
foreignField: "login",
as: "partnerData"
}
},{
//Limit fields
$project:{
"email":1,
"name":1,
"mobile":1,
"status" : 1,
"courses":"$partnerData.courses",
"examScore" : "$partnerData.examScore",
"examCompleted" : "$partnerData.examCompleted",
"login":"$partnerData.login"
}
},
{
//Join third collection
$lookup:{
from: "PartnerMetaInfo",
localField: "login",
foreignField: "partnerId",
as: "partnerMetaInfo"
}
},
//Remove from partnerData array and place at root level.
{
$unwind:
{
path: '$courses',
preserveNullAndEmptyArrays: true
}
},{
$unwind:
{
path: '$examScore',
preserveNullAndEmptyArrays: true
}
},{
$unwind:
{
path: '$examCompleted',
preserveNullAndEmptyArrays: true
}
},{
$unwind:
{
path: '$login',
preserveNullAndEmptyArrays: true
}
},//Bring $partnerMetaInfo array to root level.
{
$unwind:
{
path: '$partnerMetaInfo',
preserveNullAndEmptyArrays: true
}
},{
$limit:10
}
];
partnerMetaInfo after $unwind ends up as object. I want to flatten it and bring it at root level.
Can any body help me with this?

If all you want to get as a result is the content of your partnerMetaInfo field then you can simply add a $replaceRoot stage at the end of your pipeline like this:
{
$replaceRoot: { "newRoot": { $ifNull: [ "$partnerMetaInfo", {} ] } }
}
Otherwise, in case you want to simply move the fields inside the partnerMetaInfo field to the root then you would use $addFields:
{
$addFields: {
"partnerMetaInfoId" : "$partnerMetaInfo._id",
"costCode" : "$partnerMetaInfo.costCode",
"hub" : "$partnerMetaInfo.hub",
"location" : "$partnerMetaInfo.location"
}
}
If you have a dynamic number of fields or do not want to hardcode field names then you can use the following logic:
{
$replaceRoot: { // merge fields of and move them all the way up
"newRoot": { $mergeObjects: [ "$$ROOT", "$partnerMetaInfo" ] }
}
}, {
$project: { // remove the "partnerMetaInfo" field
"partnerMetaInfo": 0
}
}

Related

improve query performance mongodb

I am using aggregation query to retrieve 20000 records. while retrieving it is taking much time. I will mention my query below, Please help me to improve the query performance.
Query:
[err, data] = await to(LeadsLog.aggregate([
{$lookup:{
from: "leads",
localField: "leadId",
foreignField: "_id",
as: "leadId"
}},
{$lookup:{
from: "company_contacts",
localField: "leadId.assignedTo",
foreignField: "_id",
as: "assignedTo"
}},
{
$unwind:{
path: "$leadId",
preserveNullAndEmptyArrays: true
}
},
{
$match:{"leadId.assignedTo":new mongoose.Types.ObjectId(userId),
"result":{$eq:null}}
},
{ '$facet' : {
metadata: [ { $count: "total" }, { $addFields: { page: 1 } } ],
data: [ { $skip: 0 }, { $limit: 20000 } ]
} }
] ));
LeadId:
{
"_id" : ObjectId("617a84b401c98424e00d1310"),
"status" : true,
"address" : "Howmif Trail",
"city" : "Kinawnet",
"state" : "LA",
"country" : "LA",
"pincode" : null,
"extraFormObject" : null,
"lead_name" : "Jayden",
"phone" : "(524) 387-4912",
"email" : "niligis#taptehe.cm",
"company" : ObjectId("6155c2758609663d10fff796"),
"createdBy" : ObjectId("6155c2758609663d10fff798"),
"createdAt" : ISODate("2021-10-28T11:08:40.433Z"),
"updatedAt" : ISODate("2021-10-30T04:43:49.490Z")
}
LeadLog:
{
"_id" : ObjectId("617a84bf01c98424e00daf52"),
"callLogId" : null,
"result" : null,
"assignedTo" : ObjectId("6155c2758609663d10fff798"),
"extraFormObject" : null,
"subResult" : null,
"apptDate" : null,
"nextcallDate" : ISODate("2021-10-28T11:02:50.516Z"),
"callDate" : null,
"leadId" : ObjectId("617a84b401c98424e00d1310"),
"company" : ObjectId("6155c2758609663d10fff796"),
"createdAt" : ISODate("2021-10-28T11:08:50.962Z"),
"updatedAt" : ISODate("2021-10-30T04:43:50.281Z")
}
Please help me with better solution. thank you.
There are a few simple tweaks that you can improve your existing query:
make intermediate result as small as possible; one of the common ways is pushing $match stages as early as possible
use Pipeline Coalescence Optimization as much as possible; one of the common tuples would be $lookup + $unwind combination
index the $match fields and $lookup fields
Based on the first 2 points, here is my suggested form of your query:
You can see result : {$eq: null} is pushed to first stage. The performance gain will depends on the selectivity of the clause.
the $lookup and $unwind leads are grouped together to utilize the coalescence optimization.
"leadId.assignedTo": new mongoose.Types.ObjectId(userId) is moved earlier to minimize intermediate result size
Don't forget to index the relevant $match fields and $lookup fields. From my personal experience, good usage of index will help most with the performance.
[err, data] = await to(LeadsLog.aggregate([
{
$match: {
"result": {
$eq: null
}
}
},
{
$lookup: {
from: "leads",
localField: "leadId",
foreignField: "_id",
as: "leadId"
}
},
{
$unwind: {
path: "$leadId",
preserveNullAndEmptyArrays: true
}
},
{
$match: {
"leadId.assignedTo": new mongoose.Types.ObjectId(userId)
}
},
{
$lookup: {
from: "company_contacts",
localField: "leadId.assignedTo",
foreignField: "_id",
as: "assignedTo"
}
},
{
"$facet": {
metadata: [
{
$count: "total"
},
{
$addFields: {
page: 1
}
}
],
data: [
{
$skip: 0
},
{
$limit: 20000
}
]
}
}
]));

Query a MongoDB collection by the property of an embedded relation

I am trying to find documents in a collection, but filtered based on the value of an embedded ObjectID relation.
Mongoose schema is as follows:
const UserQualificationSchema = new Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
}
const UserSchema = new Schema(
{
fleet: {
type: [String], // Eg ["FleetA", "FleetB", "FleetC"]
required: true,
}
}
I need to find all UserQualifications where an item in the user's fleet equals a value in a filter array.
For example: Find all User Qualifications where user.fleet: {$in: ["FleetA", "FleetC"]}
I've looked at aggregations and querying inside .populate() but can't seem to get it to work.
Any ideas much appreciated.
Use aggregation query for your problem, I have created a query for you.
users.collection.json
/* 1 */
{
"_id" : ObjectId("61056c4a8cca27df3db2e4c8"),
"firstName" : "Rahul",
"lastName" : "soni",
"fleet" : [
"FleetA",
"FleetB",
"FleetC"
],
"createdAt" : ISODate("2021-07-31T15:29:14.918Z")
}
userqualifications.collection.json
/* 1 */
{
"_id" : ObjectId("61056c908cca27df3db2e4c9"),
"user" : ObjectId("61056c4a8cca27df3db2e4c8"),
"createdAt" : ISODate("2021-07-31T15:30:24.510Z")
}
aggregation query:
it will get the result only if a user has FleetA and FleetC.
if anyone is not matched then it will return 0 records
db.userqualifications.aggregate([{
"$lookup": {
"from": "users",
"localField": "user",
"foreignField": "_id",
"as": "user"
}
}, {
"$unwind": "$user"
}, {
"$match": {
"user.fleet": {
"$elemMatch": {
"$eq": "FleetA",
"$eq": "FleetC"
}
}
}
}])
Result:
/* 1 */
{
"_id" : ObjectId("61056c908cca27df3db2e4c9"),
"user" : {
"_id" : ObjectId("61056c4a8cca27df3db2e4c8"),
"firstName" : "Rahul",
"lastName" : "soni",
"fleet" : [
"FleetA",
"FleetB",
"FleetC"
],
"createdAt" : ISODate("2021-07-31T15:29:14.918Z")
},
"createdAt" : ISODate("2021-07-31T15:30:24.510Z")
}
if the goal is to get only UserQualifications then the following should be an efficient way as it can use an index on the fleet field of the User collection.
db.User.aggregate([
{
$match: {
fleet: { $in: ["FleetA", "FleetB"] }
}
},
{
$lookup: {
from: "UserQualification",
localField: "_id",
foreignField: "user",
as: "qualifications"
}
},
{
$unwind: "$qualifications"
},
{
$replaceWith: "$qualifications"
}
])
on the other hand if you start from the UserQualifications collection, you can't efficiently narrow down the records as you're filtering on something that it doesn't have the data for.
Thank you for the answer - it did achieve the results I was looking for - however I am now struggling to add a $match with $and to the aggregate to only return the qualifications where the user ID equals one inside a submitted array AND a given fleet.
I have the following aggregate:
db.UserQualifications.aggregate([{
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{
$unwind: '$user',
},
{
$match: {
$and: [
'user.fleet': {
$in: ["Fleet A", "Fleet C"], // This works on it's own
},
user: { // Also tried 'user._id'
$in: ["6033e4129070031c07fbbf29"] // Adding this returns blank array
}
]
},
}
}])
I have double checked that I am passing in the correct User ID's inside the arrays, but when I add this to the $and inside match, it only returns a blank array.
Is there another way to do this?
// Updated users collection
/* 1 */
{
"_id" : ObjectId("61056c4a8cca27df3db2e4c8"),
"firstName" : "Rahul",
"lastName" : "soni",
"fleet" : [
"Fleet A",
"Fleet B",
"Fleet C"
],
"createdAt" : ISODate("2021-07-31T15:29:14.918Z")
}
Query:
// userqualifications => this is my collection name, you can add your collection name here db.<YOUR>
db.userqualifications.aggregate([{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{
$unwind: '$user',
},
{
$match: {
// $and operatory syntax [{}, {}]
$and: [{
'user.fleet': {
// "Fleet A", "Fleet C" (FleetA, FleetC) this is the my first options,
// I have changes according to your problem
$in: ["Fleet A", "Fleet C"], // This works on it's own
}
}, {
// Convert user id to ObjectId type (_bsonType)
"user._id": ObjectId("61056c4a8cca27df3db2e4c8")
}]
}
}
])
Result:
/* 1 */
{
"_id" : ObjectId("61056c908cca27df3db2e4c9"),
"user" : {
"_id" : ObjectId("61056c4a8cca27df3db2e4c8"),
"firstName" : "Rahul",
"lastName" : "soni",
"fleet" : [
"Fleet A",
"Fleet B",
"Fleet C"
],
"createdAt" : ISODate("2021-07-31T15:29:14.918Z")
},
"createdAt" : ISODate("2021-07-31T15:30:24.510Z")
}
Difference Image:

MongoDB : add New Field to existing sub document after $look stage or merge lookup response to main document

I want new field "isActive" inside modifierStatus sub document which is coming from modifieritems collection.
modifieritems collection :
{
"_id" : ObjectId("5e6a5a0e6d40624b12453a67"),
"modifierName" : "xxx",
"isActive" : 1
}
{
"_id" : ObjectId("5e6a5a0e6d40624b12453a6a"),
"modifierName" : "yyy",
"isActive" : 0
}
favoritedrinks collection :
{
"alcoholName" : "whiskey",
"modifierList" : [{
"_id" : ObjectId("5e6a5a0e6d40624b12453a61"),
"modifierId" : ObjectId("5e6a5a0e6d40624b12453a67"),
"modifierName" : "xxx",
}
{
"_id" : ObjectId("5e6a5a0e6d40624b12453a66"),
"modifierId" : ObjectId("5e6a5a0e6d40624b12453a6a"),
"modifierName" : "yyy",
}]
}
my query is :
db.getCollection('favoritedrinks').aggregate([
{ "$sort": { "alcoholName": 1 } },
{"$lookup": {
"from": "modifieritems",
localField: 'modifierList.modifierId',
foreignField: '_id',
as: 'modifier'
}},
{
$project:{
"alcoholName" : "$alcoholName",
"modifierStatus":"$modifier",
}
},
]);
But my expected result :
{
"alcoholName" : "Whiskey",
"modifierStatus" : [
{
"_id" : ObjectId("5e6a5a0e6d40624b12453a61"),
"modifierId" : ObjectId("5e6a5a0e6d40624b12453a67"),
"modifierName" : "xxx",
"isActive" : 1,
},
{
"_id" : ObjectId("5e6a5a0e6d40624b12453a66"),
"modifierId" : ObjectId("5e6a5a0e6d40624b12453a6a"),
"modifierName" : "yyy",
"isActive" : 0,
}
]
}
anyone please help me?
Try this query :
Update with new requirement :
db.favoritedrinks.aggregate([
{
"$sort": {
"alcoholName": 1
}
},
{
"$lookup": {
"from": "modifieritems",
localField: "modifierList.modifierId",
foreignField: "_id",
as: "modifierStatus"
}
},
{
$addFields: {
modifierStatus: {
$map: {
input: "$modifierList",
as: "m",
in: {
$mergeObjects: [
{
$arrayElemAt: [ /** As filter would only get one object (cause you'll have only one matching doc in modifieritems coll for each "modifierList.modifierId", So getting first element out of array, else you need to take this array into an object & merge that field to particular object of 'modifierList') */
{
$filter: {
input: "$modifierStatus",
cond: {
$eq: [
"$$this._id",
"$$m.modifierId"
]
}
}
},
0
]
},
"$$m"
]
}
}
}
}
},
{
$project: {
modifierStatus: 1,
alcoholName: 1,
_id: 0
}
}
])
Test : MongoDB-Playground
Old :
db.favoritedrinks.aggregate([
{
"$sort": {
"alcoholName": 1
}
},
{
$lookup: {
from: "modifieritems",
let: {
id: "$modifierList.modifierId"
},
pipeline: [
{
$match: { $expr: { $in: ["$_id", "$$id"] } }
},
/** Adding a new field modifierId(taken from _id field of modifieritems doc)
* to each matched document from modifieritems coll */
{
$addFields: {
modifierId: "$_id"
}
}
],
as: "modifierStatus"
}
},
/** By mentioning 0 to particular fields to remove them & retain rest all other fields */
{
$project: {
modifierList: 0,
_id: 0
}
}
])
Test : MongoDB-Playground
When you want $project to include a field's current value while keeping the same field name, you need only specify :1. When you use "$field" you are explicitly setting the value, which will overwrite any existing value.
Try making your projection:
{
$project:{
"alcoholName" : 1,
"modifier.isActive": 1,
"modifier.modifierName": 1
}
}

Mongoose: how to use aggregate and flatten subdocument to list

How can i get this result in this situation?
I have one collection named coins
[
{
"_id" : ObjectId("5dc8c47f638267be1b00e808"),
"mintTxid" : "abc371bb13034ed6acf96a39e09b22347f0038002eb8a21493032885ba6b77da",
"address" : "mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow",
"spentTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46"
},
{
"_id" : ObjectId("5dc91d0d638267be1b21c2eb"),
"mintTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"address" : "mwE7bR8nLF9G1jUY17DzRhdWRrs4fGppvA"
}
]
I used $lookup and joined itself(spentTxid = mintTxid)
db.getCollection('coins').aggregate([
{ $match: {'address': 'mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow'}},
{
$lookup: {
from: 'coins',
localField: 'spentTxid',
foreignField: 'mintTxid',
as: 'spents'
}
},
{
$unwind: {
path: '$spents',
preserveNullAndEmptyArrays: true
}
}
])
And here is a result
{
"_id" : ObjectId("5dc8c47f638267be1b00e808"),
"mintTxid" : "abc371bb13034ed6acf96a39e09b22347f0038002eb8a21493032885ba6b77da",
"address" : "mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow",
"spentTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"spents" : {
"_id" : ObjectId("5dc91d0d638267be1b21c2eb"),
"mintTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"address" : "mwE7bR8nLF9G1jUY17DzRhdWRrs4fGppvA",
}
}
How can i get a result like this? i used $replaceRoot option, But that option return only child.
[
{
"_id" : ObjectId("5dc8c47f638267be1b00e808"),
"mintTxid" : "abc371bb13034ed6acf96a39e09b22347f0038002eb8a21493032885ba6b77da",
"address" : "mokZmpYj3vSqghQaZXZ8AGt1oo1HyidLow",
"spentTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
},
{
"_id" : ObjectId("5dc91d0d638267be1b21c2eb"),
"mintTxid" : "fddc7f7c6492e0cf670ff4f96e7aaaeeee3d75c51538a35286b66b6707260b46",
"address" : "mwE7bR8nLF9G1jUY17DzRhdWRrs4fGppvA",
}
]
Please help me...
After aggregate add below pipeline stages and then try:
{
$project: {
array: {
$concatArrays: [
[
{
_id: "$$ROOT._id",
address: "$$ROOT.address",
mintTxid: "$$ROOT.mintTxid",
spentTxid: "$$ROOT.spentTxid",
}
],
[
"$$ROOT.spents"
]
]
}
}
},
{
$unwind: "$array"
},
{
$replaceRoot: {
newRoot: "$array"
}
}
in project we create a new array in which we push two arrays as per our requirements
unwind the array
replace root with data in ROOT

Mogodb Aggregation

This is my user collection
{
"_id" : ObjectId("58e8cb640f861e6c40627a06"),
"actorId" : "665991",
"login" : "petroav",
"gravatar_id" : "",
"url" : "https://api.github.com/users/petroav",
"avatar_url" : "https://avatars.githubusercontent.com/u/665991?"
}
This is my repo collection
{
"_id" : ObjectId("58e8cb640f861e6c40627a07"),
"repoId" : "28688495",
"name" : "petroav/6.828",
"url" : "https://api.github.com/repos/petroav/6.828"
}
This is my events collections
{
"_id" : ObjectId("58e8cb640f861e6c40627a08"),
"eventId" : "2489651045",
"type" : "CreateEvent",
"actorLogin" : "petroav",
"repoId" : "28688495",
"eventDate" : ISODate("2015-01-01T15:00:00.000+0000"),
"public" : true
}
I am trying to do following queries on above data
Return list of all repositories with their top contributor
Find the repository with the highest number of events from an actor (by login). If multiple repos have the same number of events, return the one with the latest event.
Return actor details and list of contributed repositories by login
I tried 3 one by doing this
db.events.aggregate(
[ {
$match:{"actorLogin":"petroav"}
},
{
$lookup:{
from:"repos",
localField:"repoId",
foreignField:"repoId",
as:"Repostory"
}
},
{
$group:{ _id : "$Repostory", repo: { $push: "$$ROOT" } }
}
]
).pretty()
Please help. I am new to mongodb.
These should work, you may have to update some of the variable names if they don't match your code exactly. Because you are using actorLogin and repoId as references instead of _id, you likely want to create indexes for the fields to help with performance.
Also you may want to add a $project stage at the end of these pipelines if you want to clean up the final formats, remove extra fields, rename fields, etc..
For Number 1
db.repos.aggregate(
[
{
$lookup:{
from:"events",
localField:"repoId",
foreignField:"repoId",
as:"Event"
}
},{
$unwind:"$Event"
},
{
$group:{
_id : {repo: "$_id", user: "$Event.actorLogin" },
contributionCount: { $sum:1 },//number of times logged in
}
},
{
$sort: {
contributionCount: -1
}
},{
$group:{
_id: {repo:'$_id.repo'},
contributionCount: {$first: '$contributionCount' },
actorLogin: {$first: '$_id.user' }
}
}
]
).then(console.log)
For Number 2
db.events.aggregate(
[ {
$match:{"actorLogin":"petroav"}
},
{
$lookup:{
from:"repos",
localField:"repoId",
foreignField:"repoId",
as:"Repostory"
}
},{
$unwind:"$Repostory"
},
{
$group:{
_id : "$Repostory",
loginCount: { $sum:1 },//number of times logged in
lastLoginDate: {$max:'$eventDate'} //largest ISODate for the repo
}
},
{
$sort: {
loginCount: -1,
date: -1
}
},
{limit:1}
]
).then(console.log)
For number 3
db.user.aggregate(
[
{
$match:{"actorLogin":"petroav"}
},
{
$lookup:{
from:"events",
localField:"actorLogin",
foreignField:"actorLogin",
as:"Events"
}
},{
$unwind:"$Events"
},
{
$lookup:{
from:"repos",
localField:"Events.repoId",
foreignField:"repoId",
as:"Repostory"
}
},{
$unwind:"$Repostory"
},{
$group: {
_id:'$actorLogin',
user: {$first:'$$ROOT'}
repos: {$addToSet:'$Repostory'}
}
}
]
).then(console.log)

Resources