logo
down
shadow

Unwind array of objects mongoDB


Unwind array of objects mongoDB

By : user2949035
Date : November 15 2020, 06:54 AM
will help you
Bit of a misnomer here. To just find the "objects" or items in a "collection" then all you really need to do is match the "object/item"
code :
db.collection.find({
    "Owners.Name": /^James/
})
db.collection.find(
    { "Owners.Name": /^James/ },
    { "Owners.$": 1 }
)
db.collection.aggregate([
    // Match the document
    { "$match": {
        "Owners.Name": /^James/
    }},

    // Flatten  or de-normalize the array
    { "$unwind": "Owners" },


    // Filter th content
    { "$match": {
        "Owners.Name": /^James/
    }},

    // Maybe group it back
    { "$group": {
        "_id": "$_id",
        "BornYear": { "$first": "$BornYear" },
        "Type": { "$first": "$Type" },
        "Ownners": { "$push": "$Owners" }
    }}
])


Share : facebook icon twitter icon
MongoDB Aggregation unwind more than one array

MongoDB Aggregation unwind more than one array


By : Hossein Najafi
Date : March 29 2020, 07:55 AM
To fix the issue you can do This is what my documents look like
code :
db.test.aggregate([
  // Summarize clicks and collect countries and domains for each code
  {
    $group: {
      _id: "$code",
      clicks: { $sum: "$clicks" },
      countries: { $push: "$countries" },
      domains: { $push: "$domains" },
    }
  },
  // Unwind array of array of sub-countries
  {
    $unwind: "$countries"
  },
  // Unwind each array of sub-countries
  {
    $unwind: "$countries"
  },
  // Summarize clicks for each sub-country
  {
    $group: {
      _id: { code: "$_id", country: "$countries.country"},
      clicks: { $min: "$clicks" }, // Keep clicks which we've summarized into the 1st $group 
      countryClick: { $sum: "$countries.clicks" },
      domains: { $first: "$domains" }, // Keep domains
    }
  },
  // Collect sub-countries into embedded document
  {
    $group: {
      _id: "$_id.code",
      clicks: { $min: "$clicks" }, // Keep clicks which we've summarized into the 1st $group 
      countries: { $push: { country: "$_id.country", clicks: "$countryClick" } },
      domains: { $first: "$domains" }, // Keep sub-domains
    }
  },
  // Unwind array of array of sub-domains
  {
    $unwind: "$domains"
  },
  // Unwind each array of sub-domains
  {
    $unwind: "$domains"
  },
  // Summarize clicks for each sub-domain
  {
    $group: {
      _id: { code: "$_id", domain: "$domains.domain", country: "$domains.country" },
      clicks: { $min: "$clicks" }, // Keep clicks which we've summarized into the 1st $group 
      domainClick: { $sum: "$domains.clicks" },
      countries: { $first: "$countries" }, // Keep sub-countries
    }
  },
  // Collect sub-domains into embedded document
  {
    $group: {
      _id: "$_id.code",
      clicks: { $min: "$clicks" }, // Keep clicks which we've summarized into the 1st $group 
      domains: { $push: { domain: "$_id.domain", country: "$_id.country", clicks: "$domainClick" } },
      countries: { $first: "$countries" }, // Keep sub-countries
    }
  },
]).pretty()
unwind and group for the nested array objects in mongodb

unwind and group for the nested array objects in mongodb


By : Leif435
Date : March 29 2020, 07:55 AM
With these it helps You need to $unwind "each" array independently:
code :
.aggregate([
  { "$unwind": { "path": "$data", "preserveNullAndEmptyArrays": true } },
  { "$unwind": { "path": "$data.car", "preserveNullAndEmptyArrays": true } },
  { "$group": {
    "_id": "$data.car.model",
    "count": { "$sum": 1 }
  }}
])
.aggregate([
  { "$project": {
    "data": {
      "$reduce": {
        "input": "$data.car",
        "initialValue": [],
        "in": {
          "$concatArrays": [ "$$value", "$$this" ]
        }
      }
    }
  }},
  { "$unwind": "$data" },
  { "$group": {
    "_id": "$data.model",
    "count": { "$sum": 1 }
  }}
])
Mongodb $unwind removes objects. if $lookup doesn't have reference

Mongodb $unwind removes objects. if $lookup doesn't have reference


By : user3018457
Date : March 29 2020, 07:55 AM
help you fix your problem If country doesn't have reference states and cities. $unwind removes country name from the collections. , just add " preserveNullAndEmptyArrays: true " to $unwind
code :
Country.aggregate([
    {
        $lookup:{
            from: 'states',
            localField:'_id',
            foreignField:'countryId',
            as:'states'
        }
    },
    {
        $unwind: {
            path: "$states",
            preserveNullAndEmptyArrays: true
        }
    },
    {
        $lookup:{
            from: 'cities',
            localField:'states._id',
            foreignField:'stateId',
            as:'states.cities'
        }
    },
    {
        $group: {
            _id: {
                _id: '$_id',
                name: '$name'
            },
            states: {
                $push: '$states'
            }
        }
    },
    {
        $project: {
            _id: '$_id._id',
            name: '$_id.name',
            states: 1
        }
    }
])
[
    {
        "states" : [ 
            {
                "cities" : []
            }
        ],
        "_id" : "5d052c76df076d23a48d22f4",
        "name" : "Iran"
    },
    {
        "states" : [ 
            {
                "cities" : []
            }
        ],
        "_id" : "5d052c76df076d23a48d4b07",
        "name" : "Indonesia"
    },
    {
        "states" : [ 
            {
                "_id" : "5d2236c37ed1112b3cc41397",
                "name" : "Andaman and Nicobar Islands",
                "countryId" : "5d052c76df076d23a48d4a3b",
                "cities" : [ 
                    {
                        "_id" : ObjectId("5d38ccb6f9c5fa48bf099027"),
                        "name" : "Port Blair",
                        "stateId" : "5d2236c37ed1112b3cc41397"
                    }
                ]
            }, 
            {
                "_id" : "5d2236c37ed1112b3cc41398",
                "name" : "Andhra Pradesh",
                "countryId" : "5d052c76df076d23a48d4a3b",
                "cities" : [ 
                    {
                        "_id" : ObjectId("5d38ccbcf9c5fa48bf09902a"),
                        "name" : "Adoni",
                        "stateId" : "5d2236c37ed1112b3cc41398"
                    }
                ]
            }
        ],
        "_id" : "5d052c76df076d23a48d4a3b",
        "name" : "India"
    }
]
MongoDB - $unwind - how to unwind more than one array in a $group aggregation

MongoDB - $unwind - how to unwind more than one array in a $group aggregation


By : jonmhutch
Date : March 29 2020, 07:55 AM
This might help you How to $unwind more than one array? Have you tried $unwinding multiple times? :)
MongoDB 'unwind' nested objects

MongoDB 'unwind' nested objects


By : Burnz Loyer
Date : March 29 2020, 07:55 AM
will be helpful for those in need I have a collection in which each document looks something like this: , You should have created you schema in following way:
Related Posts Related Posts :
  • Regex replace hexadecimal characters
  • Pasting character vectors, removing NA's and separators between NAs
  • Perl: basic perl regex parsing for word@word
  • %0 is not replaced by server name when used with Apache's ProxyPassMatch
  • Regular expression for two fields on JSON response - Jmeter
  • Adding to the requirejs optimizer fileExclusionRegExp
  • grep file with full contain string
  • merge two regular expressions in vs2010
  • Get substring up until the first question mark
  • Regular expression to match part of word
  • editing a JSON file with sed
  • R: RegEx for coordinates
  • Regex 5 digits number from Subject Line in MS Outlook
  • PERL: Matching multiple patterns
  • Extract location data using regex in R
  • Extracting Dates Using Regular Expression in R using grepl
  • Regex with multiple optional groups
  • Pseudo currency regex
  • Subject to permlink convertion in bash
  • Regular expression replace all occurrences of any word beginning with a certain substring
  • Umbraco 7 regex error: Value is invalid, it does not match the correct pattern
  • Regex using Vala and GLib
  • How to match multi-row data using regular expression R programming
  • Capitalize words in a bash variable using sed
  • Find last 30 occurrences of a string in a log file using Perl
  • How to use regex in bash for selecting a string between double quotes?
  • Golang to match dash(hyphen) character
  • How to express a escape sequence in regex. ("" -> ")
  • Regular Expression - Perl
  • Regex That Pulls Certain Bits From a String
  • Regex: This or that or none
  • Copying text from one line to another
  • find string that consists only of a certain set of characters
  • Sublime Text 3: How to change the notation from ``->cls`` to some macro?
  • VBScript Return an entire line when searching for a string
  • To delete the last character with regex
  • Understanding negative lookahead
  • How can I exclude a string if it ends in ".d.ts"?
  • Need help regarding forming a regular expression -xml
  • Using sed to replace string in file by using regex capture group
  • How to match a sequence of whitespaces with c++11 regex
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org