Nested conditions in $cond aggregate - mongodb

I'm trying to create a computed status field in my Mongo query (statuses: created, payment received, shipped, received, finished).
db.orders.aggregate( [
{ $project: { status: {
$cond: { if: { $ne: ["$feedback", null] },
then: 'finished', else: {
$cond: { if: { $ne: ["$received", null] },
then: 'received', else: {
$cond: { if: { $ne: ["$shipped", null] },
then: 'shipped', else: {
$cond: { if: { $ne: ["$payment", null] },
then: 'payment received', else: 'created' }
} }
} }
} }
} } },
{ $match: { } }
] )
Example data:
{
"_id" : "xxxxxx0",
"payment" : ISODate("2016-02-03T10:45:00.011Z"),
"shipped" : ISODate("2016-02-03T11:55:00.011Z"),
"received" : ISODate("2016-02-03T12:45:00.011Z"),
"feedback" : ISODate("2016-02-03T14:34:00.011Z")
},
{
"_id" : "xxxxxx1",
"payment" : ISODate("2016-02-03T10:45:00.011Z"),
"shipped" : ISODate("2016-02-03T11:55:00.011Z"),
"received" : ISODate("2016-02-03T12:45:00.011Z")
},
{
"_id" : "xxxxxx2",
"payment" : ISODate("2016-02-03T10:45:00.011Z"),
"shipped" : ISODate("2016-02-03T11:55:00.011Z")
},
{
"_id" : "xxxxxx3",
"payment" : ISODate("2016-02-03T10:45:00.011Z")
},
{
"_id" : "xxxxxx4"
}
For some reason all my results show up as 'finished', am I using $cond wrong? Does it support nested $cond ?

You can't use $eq null if you want to check if the field exists or not, it will always return true
There is a trick to do that with $gt. You can check full explanation here (https://docs.mongodb.com/manual/reference/bson-types/#bson-types-comparison-order)
db.orders.aggregate( [
{ $project: { status: {
$cond: { if: { $gt: ["$feedback", null] },
then: 'finished', else: {
$cond: { if: { $gt: ["$received", null] },
then: 'received', else: {
$cond: { if: { $gt: ["$shipped", null] },
then: 'shipped', else: {
$cond: { if: { $gt: ["$payment", null] },
then: 'payment received', else: 'created' }
} }
} }
} }
} } },
{ $match: { } }
] )

Related

How to remove field conditionally mongoodb

I have a collection and its documents look like:
{
_id: ObjectId('111111111122222222223333'),
my_array: [
{
id: ObjectId('777777777788888888889999')
name: 'foo'
},
{
id: ObjectId('77777777778888888888555')
name: 'foo2'
}
//...
]
//more attributes
}
However, some documents have my_array: [{}] (with one element which is an empty array).
How can I add conditionally a projection or remove it?
I have to add it to a mongo pipeline at the end of the query, and I want to get my_array only when it has at least one element which is not an empty object. If there's an empty object remove it.
I tried with $cond and $eq in a projection stage but it is not supported. Any suggestion to solve this?
Suppose you have documents like this with my_array field:
{ "my_array" : [ ] }
{ "my_array" : [ { "a" : 1 } ] } // #(1)
{ "my_array" : null }
{ "some_fld" : "some value" }
{ "my_array" : [ { } ] }
{ "my_array" : [ { "a" : 2 }, { "a" : 3 } ] } // #(2)
And, the following aggregation will filter and the result will have the two documents (1) and (2):
db.collection.aggregate([
{
$match: {
$expr: {
$and: [
{ $eq: [ { $type: "$my_array" }, "array" ] },
{ $gt: [ { $size: "$my_array" }, 0 ] },
{ $ne: [ [{}], "$my_array" ] }
]
}
}
}
])
This also works with a find method:
db.collection.find({
$expr: {
$and: [
{ $eq: [ { $type: "$my_array" }, "array" ] },
{ $gt: [ { $size: "$my_array" }, 0 ] },
{ $ne: [ [{}], "$my_array" ] }
]
}
})
To remove the my_array field, from a document when its empty, then you try this aggregation:
db.collection.aggregate([
{
$addFields: {
my_array: {
$cond: [
{$and: [
{ $eq: [ { $type: "$my_array" }, "array" ] },
{ $gt: [ { $size: "$my_array" }, 0 ] },
{ $ne: [ [{}], "$my_array" ] }
]},
"$my_array",
"$$REMOVE"
]
}
}
}
])
The result:
{ }
{ "my_array" : [ { "a" : 1 } ] }
{ }
{ "a" : 1 }
{ }
{ "my_array" : [ { "a" : 2 }, { "a" : 3 } ] }
You can't do that in a query, however in an aggregations you can add $filter to you pipeline, like so:
db.collection.aggregate([
{
$project: {
my_array: {
$filter: {
input: "$my_array",
as: "elem",
cond: {
$ne: [
{},
"$$elem"
]
}
}
}
}
}
])
Mongo Playground
However unless this is "correct" behavior I suggest you clean up your database, it's much simpler to maintain "proper" structure than to update all your queries everywhere.
You can use this update to remove these objects:
db.collection.update({
"myarray": {}
},
[
{
"$set": {
"my_array": {
$filter: {
input: "$my_array",
as: "elem",
cond: {
$ne: [
{},
"$$elem"
]
}
}
}
}
},
],
{
"multi": false,
"upsert": false
})
Mongo Playground

Aggregate and project with multiples conditions

I have a collection myCollection with array of members :
{
name : String,
members: [{status : Number, memberId : {type: Schema.Types.ObjectId, ref: 'members'}]
}
and i have this data
"_id" : ObjectId("5e83791eb49ab07a48e0282b")
"members" : [
{
"status" : 1,
"_id" : ObjectId("5e83791eb49ab07a48e0282c"),
"memberId" : ObjectId("5e7dbf5b257e6b18a62f2da9")
},
{
"status" : 2,
"_id" : ObjectId("5e837944b49ab07a48e0282d"),
"memberId" : ObjectId("5e7de2dbe027f43adf678db8")
}
],
I want to check by aggregate query if member 5e7dbf5b257e6b18a62f2da9 exists with status 1 but it didn't return true
db.getCollection('myCollection').aggregate([
{$match: {_id: ObjectId("5e83791eb49ab07a48e0282b")}},
{
$project: {
isMember: {
$cond: [
{ $and: [ {$in: [ObjectId("5e7dbf5b257e6b18a62f2da9"), '$members.memberId']}, {$eq: ['$members.status', 1]} ] },
// if
true, // then
false // else
]
}
}
}
])
Thank you for your responses.
If you want to get just true/false you can shortcut like this:
db.collection.aggregate([
{ $match: { _id: ObjectId("5e83791eb49ab07a48e0282b") } },
{
$project: {
isMember: {
$map: {
input: "$members",
in: {
$and: [
{ $eq: [ObjectId("5e7dbf5b257e6b18a62f2da9"), '$$this.memberId'] },
{ $eq: [1, '$$this.status'] }
]
}
}
}
}
},
{ $set: { isMember: { $anyElementTrue: "$isMember" } } }
])
A different style would be this:
db.collection.aggregate([
{ $match: { _id: ObjectId("5e83791eb49ab07a48e0282b") } },
{
$project: {
isMember: {
$map: {
input: "$members",
in: {
$eq: [
{ memberId: ("5e7dbf5b257e6b18a62f2da9"), status: 1 },
{ memberId: "$$this.memberId", status: "$$this.status" }
]
}
}
}
}
},
{ $set: { isMember: { $anyElementTrue: "$isMember" } } }
])

MongoDB If condition as the second field in gt

I want to select the $user_a_seen_at field if $user_a_id == socket.user_id otherwise select the $user_b_seen_at field. But my query isn't working.
$gt: ["$$this.created_at", IF CONDITION TO SELECT A FIELD ]
$project: {
unread_messages: {
$size: {
$filter: {
input: "$messages",
cond: {
$and: [
{ $eq: ["$$this.to_id", socket.user_id] },
{
$gt: [
"$$this.created_at", {
if: { $eq: ["$user_a_id", socket.user_id] },
then: "$user_a_seen_at",
else: "$user_b_seen_at"
}
]
}
]
}
}
}
}
}
Sample data
{
"_id" : ObjectId("5e4c57649fad2e2cac9f8cd5"),
"user_a_id" : 1,
"user_b_id" : 2,
"user_a_seen_at" : ISODate("2020-02-18T21:30:12.418Z"),
"user_b_seen_at" : ISODate("2020-02-18T15:30:12.418Z"),
"messages" : [
{
"text" : "Hello",
"_id" : ObjectId("5e4c57649fad2e2cac9f8cd4"),
"from_id" : 1,
"to_id" : 2,
"created_at" : ISODate("2020-02-18T21:30:12.409Z")
}
],
"created_at" : ISODate("2020-02-18T21:30:12.418Z"),
"last_activity" : ISODate("2020-02-18T21:30:12.418Z"),
"__v" : 0
}
You need to use $cond operator to evaluate a boolean expression to return one of the two specified return expressions
{ $cond: { if: <boolean-expression>, then: <true-case>, else: <false-case> } }
//or simplified
{ $cond: [ <boolean-expression>, <true-case>, <false-case> ] }
db.collection.aggregate([
{
$project: {
unread_messages: {
$size: {
$filter: {
input: "$messages",
cond: {
$and: [
{
$eq: [
"$$this.to_id",
socket.user_id
]
},
{
$gt: [
"$$this.created_at",
{
$cond: [
{
$eq: [
"$user_a_id",
socket.user_id
]
},
"$user_a_seen_at",
"$user_b_seen_at"
]
}
]
}
]
}
}
}
}
}
}
])
MongoPlayground

Query datevalue of a inner Array element

Need help with some MongoDB query:
The document I have is below and I am trying to search based on 2 conditions
The meta.tags.code = "ABC"
Its LastSyncDateTime should
meta.extension.value == "" (OR)
the meta.extension.value is less than meta.lastUpdated
Data :
{
"meta" : {
"extension" : [
{
"url" : "LastSyncDateTime",
"value" : "20190206-00:49:25.694"
},
{
"url" : "RetryCount",
"value" : "0"
}
],
"lastUpdate" : "20190207-01:21:41.095",
"tags" : [
{
"code" : "ABC",
"system" : "type"
},
{
"code" : "XYZ",
"system" : "SourceSystem"
}
]
}
}
Query:
db.proc_patients_service.find({
"meta.tags.code": "ABC",
$or: [{
"meta.extension.value": ""
}, {
$expr: { "$lt": [{ "mgfunc": "ISODate", "params": [{ "$arrayElemAt": ["$meta.extension.value", 0] }] }, { "mgfunc": "ISODate", "params": ["$meta.lastUpdate"] }] }
}]
})
But it is only fetching ABC Patients whose LastSyncDateTime is empty and ignores the other condition.
Using MongoDB Aggregation, I have converted your string to date with operator $dateFromString and then compare the value as per your criteria.
db.proc_patients_service.aggregate([
{ $match: { "meta.tags.code": "ABC", } },
{ $unwind: "$meta.extension" },
{
$project: {
'meta.tags': '$meta.tags',
'meta.lastUpdate': { '$dateFromString': { 'dateString': '$meta.lastUpdate', format: "%Y%m%d-%H:%M:%S.%L" } },
'meta.extension.url': '$meta.extension.url',
'meta.extension.value': {
$cond: {
if: { $ne: ["$meta.extension.value", "0"] }, then: { '$dateFromString': { 'dateString': '$meta.extension.value', format: "%Y%m%d-%H:%M:%S.%L" } }, else: 0
}
}
}
},
{
$match: {
$or: [
{ "meta.extension.value": 0 },
{ $expr: { $lt: ["$meta.extension.value", "$meta.lastUpdate"] } }
]
}
},
{
$group: { _id: '_id', 'extension': { $push: '$meta.extension' }, "lastUpdate": { $first: '$meta.lastUpdate' }, 'tags': { $first: '$meta.tags' } }
},
{
$project: { meta: { 'extension': '$extension', lastUpdate: '$lastUpdate', 'tags': '$tags' } }
}
])

Mongo Db query using if condition

I have a Mongodb Data which looks like this
{
"userId" : "123",
"dataArray" : [
{
"scheduledStartDate" : ISODate("2018-08-30T11:34:36.000+05:30"),
"scheduledEndDate" : ISODate("2018-08-30T11:34:36.000+05:30"),
"Progress" : 0,
"ASD":""
},
{
"scheduledStartDate" : ISODate("2018-09-22T11:34:36.000+05:30"),
"scheduledEndDate" : ISODate("2018-10-01T11:34:36.000+05:30"),
"Progress" : 0,
"ASD":ISODate("2018-08-30T11:34:36.000+05:30"),
}
],
"userStatus" : 1,
"completionStatus" : "IP",
}
I want to find those document where condition is something like this
(PROGRESS<100||(PROGRESS==100&&ASD not exists)).
This should get you going ($elemMatch):
db.collection.find({
dataArray: {
$elemMatch: {
$or: [
{ Progress: { $lt: 100 } },
{ $and: [
{ Progress: { $eq: 100 } },
{ ASD: { $exists: false } }
]}
]
}
}
})
UPDATE based on your comment - this is even easier:
db.collection.find({
$or: [
{ "dataArray.Progress": { $lt: 100 } },
{ $and: [
{ "dataArray.Progress": { $eq: 100 } },
{ "dataArray.ASD": { $exists: false } }
]}
]
})