i am trying to fetch data from collection form below query:
db.getCollection('jobs').aggregate(
{$match :{"slug":"bath-room-designer-for-whole-floor-772000"}},
{$unwind: "$job_activity"},
{$lookup: {
"from":"users",
"localField":"job_activity.user_id",
"foreignField":"_id",
"as": "user_details"
}
},
{$unwind: { path: "$user_details", preserveNullAndEmptyArrays: false } },
{$group: {
"_id": "$_id",
"Job_detail": {"$push": "$job_activity"},
"job_activity": {"$push": "$job_activity"},
"user_details": {"$push": "$user_details"}
}
}
)
But it result empty data wherever datat exists in the collection for the $match but job_activity is not exist for this slug
can anyone help Thanks
Missing Field If you specify a path for a field that does not exist in an input document or the field is an empty array, $unwind , by default, ignores the input document and will not output documents for that input document.
In MongoDB, we can check the existence of the field in the specified collection using the $exists operator. When the value of $exists operator is set to true, then this operator matches the document that contains the specified field(including the documents where the value of that field is null).
You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});
The MongoDB $unwind stages operator is used to deconstructing an array field from the input documents to output a document for each element. Every output document is the input document with the value of the array field replaced by the element. Points to remember: If the value of a field is not an array, db.
use the preserveNullAndEmptyArrays of $unwind to keep documents where job_activity
doesn't exist or is empty
so use this $unwind
stage:
{
$unwind:
{
path: "$job_activity",
preserveNullAndEmptyArrays: true
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With