getting problem with condition in mongodb - mongodb

See my condition does work fine for my history's first collection but for second it does not work either If I replace my specified id with 5e4a8d2d3952132a08ae5724 that exists in my second object of history's collection return me all data which is not correct because it's date is greater then main collection's date so it should return me nothing please suggest how to fix it.
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$unwind: "$History"
},
{
"$match": {
$expr: {
$cond: {
if: {
$eq: [
"5e4a8d2d3952132a08ae5764",
"$History.user_id"
]
},
then: {
$and: [
{
$gt: [
"$date",
"$History.date"
]
},
{
$eq: [
"5e4a8d2d3952132a08ae5764",
"$History.user_id"
]
}
]
},
else: {}
}
}
}
}
])
when I put two object into history collection it does not work either MongoPlayground
Here is working playground with single history object https://mongoplayground.net/p/hrNofrq1c3S

The reason, why your query (which is posted in the OP) is not working because, you have not specified anything in else part. So, the better approach will be with '$filter' operator.
You can try the below:
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$project: {
"History": {
$filter: {
input: "$History",
as: "his",
cond: {
$and: [
{
$lt: [
"$$his.date",
"$date"
]
},
{
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
}
]
}
}
},
data: 1,
history_id: 1,
sender_id: 1,
text: 1,
date: 1
}
},
{
$unwind: "$History"
}
])
MongoPlayGroundLink

Related

mongodb - Multiple LET and AS assignments to use within the same pipeline

How to perform multiple let and as and use them within the same pipeline. I have the following query but assignment defaults to userTo. Both userFrom and userTo are from users collection
{
$lookup: {
from: "users",
let: {
userFrom: "$from",
},
as: "userFrom",
let: {
userTo: "$to",
},
as: "userTo",
pipeline: [
{
$match: {
$expr: {
$or: [
{
$eq: [
"$$userFrom",
"$_id"
]
},
{
$eq: [
"$$userTo",
"$_id"
]
}
]
}
}
},
You are not using them correctly. as specifies the name of the output array of the $lookup. There is only 1 result set per lookup so only 1 as would be needed.
let specifies the variables you want to use in the sub-pipeline. You can put them in an object if you want to use multiple variables.
Your code should look like this:
db.collection.aggregate([
{
$lookup: {
from: "users",
let: {
userFrom: "$from",
userTo: "$to"
},
pipeline: [
{
$match: {
$expr: {
$or: [
{
$eq: [
"$$userFrom",
"$_id"
]
},
{
$eq: [
"$$userTo",
"$_id"
]
}
]
}
}
}
],
as: "userLookup"
}
}
])

Check for non-existing field in lookup pipeline

How to check if a field is not existing inside lookup expression? The answers in similar questions are not helpful (e.g. {$eq : null} or $exists:true).
For example, I want to lookup inventory only if disabled is not existing.
db.orders.aggregate([
{
$lookup: {
from: "inventory",
let: {item: "$item"},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ["$sku", "$$item" ]
},
{
$eq: [ "$disabled", null ]
}
]
}
}
},
],
as: "inv"
}
}
])
A playground sample is here
You can use $exists outside the $expr:
db.orders.aggregate([
{
$lookup: {
from: "inventory",
let: {item: "$item"},
pipeline: [
{
$match: {
$and: [
{$expr: {$eq: ["$sku", "$$item"]}},
{disabled: {$exists: false}}
]
}
}
],
as: "inv"
}
}
])
See how it works on the playground example
you could use:
{ $match: { someField: { $exists: true } } }
before the look up, to filter out the documents that you do not want to look up

MongoDb return records only if $lookup cond is occur

I have a class model which has field ref.
I'm trying to fetch only records that match the condition in lookup.
so what i did:
{
$lookup: {
from: 'fields',
localField: "field",
foreignField: "_id",
as: 'FieldCollege',
},
},
{
$addFields: {
"FieldCollege": {
$arrayElemAt: [
{
$filter: {
input: "$FieldCollege",
as: "field",
cond: {
$eq: ["$$field.level", req.query.level]
}
}
}, 0
]
}
}
},
The above code works fine and returning the FieldCollege if the cond is matched.
but the thing is, i wanted to return the class records only if the FieldCollege is not empty.
I'm totally new to mongodb. so i tried something like this:
{
$match: {
'FieldCollege': { $exists: true, $ne: [] }
}
},
Obv this didn't work.
does mongodb support something like this or am i complicating things?
EDIT:
the result from the above code:
"Classes": [
{
"_id": "613245664c6ea614e001fcef",
"name": "test",
"language": "en",
"year_cost": "3232323",
"FieldCollege":[] // with $unwind
}
],
expected Result:
"Classes": [
// FieldCollege is empty
],
I think the good option is to use lookup with pipeline, and see the final version of your query,
$lookup with fields collection and match your both conditions
$limit to result one document
$match FieldCollege is not empty []
$addElemAt to get first element from result FieldCollege
[
{
$lookup: {
from: "fields",
let: { field: "$field" },
pipeline: [
{
$match: {
$and: [
{ $expr: { $eq: ["$$field", "$_id"] } },
{ level: req.query.level }
]
}
},
{ $limit: 1 }
],
as: "FieldCollege"
}
},
{ $match: { FieldCollege: { $ne: [] } } },
{
$addFields: {
FieldCollege: { $arrayElemAt: ["$FieldCollege", 0] }
}
}
]

Mongodb if then condition under filter how to make

db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}
},
{
$project: {
"History": {
$filter: {
input: "$History",
as: "his",
if: {
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
},
then: {
cond: {
$and: [
{
$lt: [
"$$his.date",
"$date"
]
},
{
$eq: [
"5e4a8d2d3952132a08ae5764",
"$$his.user_id"
]
}
]
}
},
else: {}
}
},
data: 1,
history_id: 1,
sender_id: 1,
text: 1,
date: 1
}
},
{
$unwind: "$History"
}
])
MongoPlayground
Play with if condition under filter getting error. My purpose is specified user_id match with history's user_id then condition work other wise not.
How to fix it please guide or alternative approaches are welcome.
After discussion in chat, it seems the overall problem was how to select documents from the main collection based on 2 criteria of the related history documents:
db.main.aggregate([
{$lookup: {
from: "history",
localField: "history_id",
foreignField: "history_id",
as: "History"
}},
{$match: {
$expr: {
$eq: [
false,
{$reduce: {
input: "$History",
initialValue: false,
in: {
$or: [
"$$value",
{$and: [
{$eq: [
"$$this.user_id",
ObjectId("5e4a8d2d3952132a08ae5764")
]},
{$gte: [
"$$this.date",
"$date"
]}
]}
]
}
}}
]
}
}}
])
Playground

$match expr in same document does not work

How to transform the data using $if $else condition MongoDB
mongoPlayground
I am getting worst digging into $if $expr condition
This playground should return nothing because date is $gt then main collection but it does return me data.
So condition should say if history's date is $gt then main collection should return nothing else return the matched criteria data.
the first history record only is used, as it has the same _id as the history_id in the main collection
so if you check the first history document
{
"_id": ObjectId("5e4e755b380054797d9db627"),
"user_id": "5e4e74eb380054797d9db625",
"history_id": ObjectId("5e4e755b380054797d9db627"),
"date": 1587650683433,
"__v": 1
}
and your query
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "_id",
as: "History"
}
},
{
$unwind: "$History"
},
{
"$match": {
$expr: {
$cond: {
if: {
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
},
then: {
$and: [
{
$gt: [
"$date",
"$History.date"
]
},
{ // also, this part has no meaning as the same condition is used in the if part
$eq: [
"5e4e74eb380054797d9db623",
"$History.user_id"
]
}
]
},
else: {}
}
}
}
}
])
the if condition is not satisfied, as the user_id in history model "5e4e74eb380054797d9db625" does not equal to the specified id "5e4e74eb380054797d9db623"
so, it goes to the else part which is getting all the documents in the main collection
note: I've added some comment in the query, could you check it too?
If I am not wrong I guess this is what you're expecting :-
db.main.aggregate([
{
$lookup: {
from: "history",
localField: "history_id",
foreignField: "_id",
as: "History"
}
},
{
$unwind: "$History"
},
{
"$match": {
$expr: {
$and: [
{
$eq: [
"$_id",
"$History.user_id"
]
},
{
$gt: [
"$date",
"$Histoy.date"
]
}
]
}
}
}
])
Well, few modification might be needed to fulfill your need.