MongoDB aggregate add new field with multiple conditions - javascript

I cannot figure to add a new field with multiple conditions in MongoDB. Here is how DB looks like,
const db = [
{
_id: 1,
isActived: false, // Drafted
isScheduled: false,
isExpired: false
},
{
_id: 2,
isActived: true,
isScheduled: true, // Scheduled
isExpired: false
},
{
_id: 3,
isActived: true, // Expired
isScheduled: false,
isExpired: true
},
{
_id: 4,
isActived: true, // Actived
isScheduled: false,
isExpired: false
},
]
Conditions are:
if (!isActived) status = "Draft"
if (isActived && isScheduled) status = "Scheduled"
if (isActived && isExpired) status = "Expired"
if (isActived && !isScheduled && !isExpired) status = "Actived"
I can figure out only one condition and cannot solve it any further. Here is what I did so far
{
$addFields: {
status: {
$cond: [
{
$and: [
{ $eq: ["$isActived", true] },
{ $eq: ["$isScheduled", true] },
],
},
"Actived",
"Scheduled",
],
$cond: [
{
$and: [
{ $eq: ["$isActived", true] },
{ $eq: ["$isExpired", true] },
],
},
"Actived",
"Expired",
],
},
},
}
The result is not what I expected.
Any suggestion. Thank You.

You can concatenate if/else in this way:
Pseudocode:
if !isActived:
return "Draft"
else
if !isScheduled && !isExpired:
return "Actived"
else
if isScheduled:
return "Scheduled"
else
return "Expired" //<-- Since one of "isScheduled" and "isExpired" should be true
Take care on last line where may you can have isScheduled and isExpired to true, so you logic can change.
db.collection.aggregate([
{
"$set": {
"status": {
"$cond": {
"if": {
"$eq": [
"$isActived",
false
]
},
"then": "Draft",
"else": {
"$cond": {
"if": {
"$and": [
{
"$eq": [
"$isExpired",
false
]
},
{
"$eq": [
"$isScheduled",
false
]
}
]
},
"then": "Actived",
"else": {
"$cond": {
"if": {
"$eq": [
"$isScheduled",
true
]
},
"then": "Scheduled",
"else": "Expired"
}
}
}
}
}
}
}
}
])
Example here

Simple nested conditions, working solution
db.collection.aggregate([
{
$addFields: {
status: {
$cond: [
{
$and: [
{ $eq: [ "$isActived", true ] },
{ $eq: [ "$isScheduled", false ] },
{ $eq: [ "$isExpired", false ] },
],
},
"Actived",
{
$cond: [
{
$and: [
{ $eq: [ "$isActived", true ] },
{ $eq: [ "$isExpired", true ] },
],
},
"Expired",
{
$cond: [
{
$and: [
{ $eq: [ "$isActived", true ] },
{ $eq: [ "$isScheduled", true ] },
],
},
"Scheduled",
{
$cond: [
{
$and: [
{ $eq: [ "$isActived", false ] },
],
},
"Draft",
null,
],
},
],
},
],
},
],
},
},
},
])

Related

Find user is registered to a Event in MongoDb (aggregation)

I tried to find users who are registered for that event.
So I join multiple collections shown below -
Events.aggregate([
{ $match: { category: "group_event" } },
// collection where events are scheduled
{
$lookup: {
from: "group_events",
let: { eventId: "$eventID" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$_id", "$$eventId"] },
{ $gt: ["$time", new Date()] },
],
},
},
},
// register user collection
{
$lookup: {
from: "register_events",
let: { eventId: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$eventId", "$$eventId"] } } },
],
as: "registerUsers",
},
},
],
as: "events",
},
},
{ $unwind: "$events" },
])
and the output is now comingout -
[
{
"_id": "614d6dfd82cb36be231083c9",
"trainerId": "61488dc36b7ccedbc884d20a",
"category": "group_event",
"eventID": "614d6dfc82cb36be231083c7",
"createdAt": "2021-09-24T06:19:41.268Z",
"updatedAt": "2021-09-24T06:19:41.268Z",
"__v": 0,
"events": {
"_id": "614d6dfc82cb36be231083c7",
"groupName": "group name 4",
"category": "sdfsdf",
"time": "2021-09-27T07:44:58.762Z",
"description": "description",
"day": "sunday",
"platform": "zoom",
"notes": "22",
"skills_to_learn": [
"demo"
],
"status": "pending",
"trainerId": "61488dc36b7ccedbc884d20a",
"meetingLink": "https://us05web.zoom.us/j/81660534858?pwd=cGZaODVjdWJUQWNtN243MlNiVUN0UT09",
"type": "group_event",
**isUserRegisted : true / false,**
"createdAt": "2021-09-24T06:19:41.000Z",
"updatedAt": "2021-09-24T06:19:41.000Z",
"__v": 0,
"registerUsers": [
{
"_id": "614ed6b4b8a545acb8517e85",
"userId": "614d59371d11becb8e23f536",
"eventId": "614d6dfc82cb36be231083c7",
"question": "",
"createdAt": "2021-09-25T07:58:44.939Z",
"updatedAt": "2021-09-25T07:58:44.939Z",
"__v": 0
}
]
}
}
]
which is ok for me bu just wanted to add a key: value, heighlited on obove section
isUserRegisted : true / false
i tried with $addFields but can't came up with any solution. Basically I need to retrieve arrays from registerUsers - collection and on the same time match the userId
I was able to figure out this issue.
simply I need to use $project and $filter to get the data if available and at last use $cond to return true or false
{
$project: {
root: "$$ROOT",
userFound: {
$filter: {
input: "$registerUsers",
as: "ac",
cond: {
$eq: ["$$ac.userId", mongoose.Types.ObjectId(userId)],
},
},
},
},
},
{
$project: {
_id: 0,
document: "$$ROOT",
userFound: {
$cond: {
if: { $isArray: "$userFound" },
then: {
$cond: {
if: {
$gt: [{ $size: "$userFound" }, 0],
},
then: true,
else: false,
},
},
else: false,
},
},
},
},
// merging nested object with parents
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$document.root",
{ isUserRegistered: "$userFound" },
],
},
},
},

Mongo DB query to return count?

I have two collections Course and File.
This is my data from Course collection
[{
_id: 1,
name: "Course1",
price: "100"
},
{
_id: 2,
name: "Course2",
price: "200"
}]
This is my data from files collection
[{
_id: 1,
name: "File1",
isFree: true,
courseId: 1
}
{
_id: 2,
name: "File2",
isFree: false,
courseId: 1
}
{
_id: 3,
name: "File3",
isFree: false,
courseId: 1
}]
I want to retrieve Course 1 with Course name,Count of files which are free,Count of files which are not free.
My attempt:
Course.aggregate([
{$lookup:{
from:"files",
localField: "_id",
foreignField: "courseId",
as: "files"
}},
])
This is my response If I execute my above query:
[
{
"_id": "6161bdcc0aada09d81598840",
"name": "Course1",
"files": [
{
"_id": "6166a0814ad3f56b71232b9c",
"name": "File1.jpeg",
"isFree":true
},
{
"_id": "6166a0814ad3f56b71232b9d",
"name": "File2.jpeg",
"isFree":false
},
{
"_id": "6166a0814ad3f56b71232b9v",
"name": "File3.jpeg",
"isFree":false
}
]
}
]
I want my output as:
[
{
"_id": "6161bdcc0aada09d81598840",
"name": "Course1",
"files": {"free": 1,"paid": 2}
}
]
You can try lookup with pipeline,
$lookup with pipeline, pass courseId in let
$match courseId condition
$group by isFeee and get total count
$project to show required fields in k(key) and v(value) format
$cond to check if isFree true then return "free" otherwise return "paid"
$addFields to update files array
$arrayToObject convert files key-value array to an object
$ifNull to check if property is not exists then set 0
await Course.aggregate([
{
$lookup: {
from: "files",
let: { courseId: "$_id" },
pipeline: [
{ $match: { $expr: { $eq: ["$$courseId", "$courseId"] } } },
{
$group: {
_id: "$isFree",
count: { $sum: 1 }
}
},
{
$project: {
_id: 0,
k: { $cond: ["$_id", "free", "paid"] },
v: "$count"
}
}
],
as: "files"
}
},
{
$addFields: {
files: { $arrayToObject: "$files" }
}
},
{
$addFields: {
"files.free": { $ifNull: ["$files.free", 0] },
"files.paid": { $ifNull: ["$files.paid", 0] }
}
}
])
Playground
Try following:
db.course.aggregate([
{
$lookup: {
from: "files",
localField: "_id",
foreignField: "courseId",
as: "files",
},
},
{
$unwind: {
path: "$files",
preserveNullAndEmptyArrays: true,
},
},
{
$group: {
_id: "$_id",
name: {
$first: "$name",
},
price: {
$first: "$price",
},
free: {
$sum: {
$cond: [
{
$eq: ["$files.isFree", true],
},
1,
0,
],
},
},
paid: {
$sum: {
$cond: [
{
$eq: ["$files.isFree", false],
},
1,
0,
],
},
},
},
},
{
$addFields: {
"files.free": "$free",
"files.paid": "$paid",
},
},
{
$project: {
_id: 1,
name: 1,
files: 1,
price: 1,
},
},
]);

How to update multiple objects in the array in mongoDB?

How to update multiple objects in the array in MongoDB? Assume that I am retrieving from the client an array of titles that need to be changed.
Example:
Data from client:
[0,3]
Document in the MongoDB:
[
{
_id: 0,
dishes: [
{ title: 0, in_stock: true },
{ title: 1, in_stock: false },
{ title: 2, in_stock: true },
{ title: 3, in_stock: false },
],
},
];
The result should be:
[
{
_id: 0,
dishes: [
{ title: 0, in_stock: false },
{ title: 1, in_stock: false },
{ title: 2, in_stock: true },
{ title: 3, in_stock: true },
],
},
];
You can simply put a aggregation pipeline in your update clause.
db.collection.update({},
[
{
"$addFields": {
"dishes": {
"$map": {
"input": "$dishes",
"as": "d",
"in": {
"$cond": {
"if": {
"$in": [
"$$d.title",
[
0,
3
]
]
},
"then": {
title: "$$d.title",
in_stock: {
"$not": [
"$$d.in_stock"
]
}
},
"else": "$$d"
}
}
}
}
}
}
])
Here is the Mongo playground for your reference.

MongoDB get max date inside double nested array

Assume I have the following document:
[
{
"callId": "17dac51e-125e-499e-9064-f20bd3b1a9d8",
"caller": {
"firstName": "Test",
"lastName": "Testing",
"phoneNumber": "1231231234"
},
"inquiries": [
{
"inquiryId": "b0d14381-ce75-49aa-a66a-c36ae20b72a8",
"routeHistory": [
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-01T06:00:00.000Z",
"status": "routed"
},
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-03T06:00:00.000Z",
"status": "ended"
}
]
},
{
"inquiryId": "9d743be9-7613-46d7-8f9b-a04b4b899b56",
"routeHistory": [
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-01T06:00:00.000Z",
"status": "routed"
},
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-03T06:00:00.000Z",
"status": "ended"
}
]
}
]
}
]
I want to get results where inquiries.routeHistory.routeDate is equal to the $max routeDate value in routeHistory. I would expect my results to look like the following:
[
{
"callId": "17dac51e-125e-499e-9064-f20bd3b1a9d8",
"caller": {
"firstName": "Test",
"lastName": "Testing",
"phoneNumber": "1231231234"
},
"inquiries": [
{
"inquiryId": "b0d14381-ce75-49aa-a66a-c36ae20b72a8",
"routeHistory": [
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-03T06:00:00.000Z",
"status": "ended"
}
]
},
{
"inquiryId": "9d743be9-7613-46d7-8f9b-a04b4b899b56",
"routeHistory": [
{
"assignedUserId": "cfa0ffe9-c77d-4eec-87d7-4430f7772e81",
"routeDate": "2020-01-03T06:00:00.000Z",
"status": "ended"
}
]
}
]
}
]
Is there a clean way to do this in a single aggregate, so that additional $match criteria can be applied? One caveat is that I can only use operators supported by DocumentDB: https://docs.aws.amazon.com/documentdb/latest/developerguide/mongo-apis.html
I have tried the following code, but to no avail:
{
$addFields: {
maxDate: {
$max: '$inquiries.routeHistory.routeDate',
},
},
},
{
$addFields: {
routeHistory: [
{
$arrayElemAt: [
{
$filter: {
input: '$inquiries.routeHistory',
cond: {
$eq: ['$maxDate', '$$this.routeDate'
],
},
},
},
0,
],
},
],
},
}
You have to use $map to scan outer array and to $filter to compare inner array's elements against $max date:
db.collection.aggregate([
{
$addFields: {
inquiries: {
$map: {
input: "$inquiries",
as: "inquiry",
in: {
inquiryId: "$$inquiry.inquiryId",
routeHistory: {
$filter: {
input: "$$inquiry.routeHistory",
cond: {
$eq: [ { $max: "$$inquiry.routeHistory.routeDate" }, "$$this.routeDate" ]
}
}
}
}
}
}
}
}
])
Mongo Playground
EDIT: by looking at your link I've noticed that $map is not supported, you can use below combination as a workaround:
db.collection.aggregate([
{
$unwind: "$inquiries"
},
{
$addFields: {
"inquiries.routeHistory": {
$filter: {
input: "$inquiries.routeHistory",
cond: {
$eq: [ { $max: "$inquiries.routeHistory.routeDate" }, "$$this.routeDate" ]
}
}
}
}
},
{
$group: {
_id: "$_id",
callId: { $first: "$callId" },
caller: { $first: "$caller" },
inquiries: { $push: "$inquiries" }
}
}
])
Mongo Playground (2)

MongoDB nested query - BadValue error

Here's the query I'm trying to run:
{ ownerId: 14,
'$or':
[ { '$or':
[ { '$and':
[ { provider: 'INSTAGRAM' },
{ tags:
{ '$or':
[ { '$in': [ 'skyhotel' ] },
{ '$or': [ { '$all': ["skyhotel","excellent"] } ] } ] } } ] },
{ '$and':
[ { provider: 'VKONTAKTE' },
{ tags:
{ '$or':
[ { '$in': [ 'skyhotel' ] },
{ '$or': [ { '$all': ["skyhotel","excellent"] } ] } ] } } ] } ] },
{ '$or':
[ { '$and':
[ { provider: 'INSTAGRAM' },
{ authorLogin: { '$in': [ 'valera92', 'petyan' ] } } ] },
{ '$and':
[ { provider: 'VKONTAKTE' },
{ authorLogin: { '$in': [ 'valera92' ] } } ] } ] },
{ '$or':
[ { '$and':
[ { provider: 'INSTAGRAM' },
{ locationId: { '$in': [ '32454234' ] } } ] } ] },
{ '$or':
[ { '$and':
[ { provider: 'INSTAGRAM' },
{ location: { '$or': [ { '$geoWithin': { '$centerSphere': [ [ '56.829782', '60.593162' ], 0.000012629451881788331 ] } } ] } } ] } ] } ] }
It seems to be malformed according to mongo standards. The error I'm getting is:
Can't canonicalize query: BadValue unknown operator: $or
What would be the proper way in which I could reformat this query?
EDIT: Document example
{
"_id" : ObjectId("570362332ee1a7ab1ecb9899"),
"proextid" : "INSTAGRAM_fdfsfsdfsdfwefwef2r3232",
"updatedAt" : ISODate("2016-04-05T06:58:59.683Z"),
"createdAt" : ISODate("2016-04-05T06:58:59.683Z"),
"ownerId" : 7,
"authorId" : "390599885",
"authorName" : "name",
"authorLogin" : "login",
"authorDetail" : {
"authorPicture" : "url",
"authorLink" : "url"
},
"externalCreatedAt" : ISODate("2015-08-29T22:42:04.000Z"),
"externalId" : "fdsfsdfsdfsdfwer2342342423423r23r",
"detailType" : "PHOTO",
"location" : [
0,
0
],
"locationId" : "",
"locationTitle" : "",
"provider" : "INSTAGRAM",
"detail" : {},
"description" : "hello",
"tags" : [
"ленинградскийпроспект",
"москва",
"архитектура",
"историческоенаследие",
"петровскийдворец"
],
"commentsCount" : 1,
"likesCount" : 40,
"groupName" : "",
"__v" : 0
}
Your query could be simplified as something like:
{
ownerId:14,
provider: { $in: [ 'INSTAGRAM', 'VKONTAKTE' ] },
'$or': [
{
tags: { $in: [ 'skyhotel', 'excellent' ] }
},
{
authorLogin: { $in: [ 'valera92', 'petyan' ] },
},
{
locationId:{ '$in':[ '32454234' ] }
},
{
location:{
{
'$geoWithin':{
'$centerSphere':[ [ '56.829782', '60.593162' ], 0.000012629451881788331 ]
}
}
}
}
]
}
Now this may not be exactly what you're looking for. But from what you asked, and the information you provided, this is the best suggestion I can give.

Categories

Resources