skip to Main Content

Initially I was trying to match by fields.locations.id, however this wasn’t returning any results surprisingly. Browsing SO I’ve seen that prior matching an $unwind has to be done so it works (don’t really know if this is still the rule in MongoDB >4.x).

Having the following document:

{
    "internalId": "idx8",
    "fields": {
        "city": "Winsconsin",
        "locations": [
            [{
                "id": "abc",
                "name": "A Bar",
                "tokens": ["A", "Bar"]
            }, {
                "id": "xyz",
                "name": "A Bus Station",
                "tokens": ["A", "Bus", "Station"]
            }]
        ],
        "extraInfo": {
            "randomMap": {
                ...
            }
        }
    }
}

Performing the following aggregation:

db.sample_collection.aggregate([
   { $unwind: { path: "$fields.locations", preserveNullAndEmptyArrays: true } }
])

This won’t really do anything to the result and documents shown by the aggregation are exactly the same. Am I doing something wrong or have I shaped the documents the wrong way?

2

Answers


  1. $unwind will unwind exactly one level of an array – because your structure has a nested array you’d need this:

    db.sample_collection.aggregate([
       { $unwind: { path: "$fields.locations", preserveNullAndEmptyArrays: true }}, 
       { $unwind: { path: "$fields.locations", preserveNullAndEmptyArrays: true }}
    ])
    

    This will give you one document per item in all of the items in locations, so if locations = [[1,2,3], [1,2,3]] – you’d get 6 rows.

    Login or Signup to reply.
  2. $unwind open up the array in collection/query.

    First of all, make your query look simple. no need to specify the path, as $unwind operator with a specific field name will auto-unwind it.

    Example:

    db.collection.aggregate( [ { $unwind: "$fields.location" } ] )
    db.collection.aggregate( [ { $unwind: { path: "$fields.location" } } ] )

    Both queries are correct.

    As far as preserveNullAndEmptyArrays is concerned this option is used to include documents whose sizes field is null, missing, or an empty array.

    db.sample_collection.aggregate([$unwind:"$fields.location"]) will work fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search