Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all result if unwind field does not exist in mongodb

Tags:

mongodb

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

like image 438
Mukesh Rawat Avatar asked Mar 30 '17 06:03

Mukesh Rawat


People also ask

What happens to an input document whose field does not exist in an $unwind operation?

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.

How do you check if a sub field is exists in MongoDB?

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).

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do you unwind an array of objects in MongoDB?

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.


1 Answers

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
    }
}
like image 54
felix Avatar answered Oct 04 '22 02:10

felix