rom
rom

Reputation: 666

How to extract the field of an array element in MongoDB Aggregation?

So, my document is like the below example.

{
    image: {imageUrl: "http://imageurlsite.com/xyz"},
    additionalImages: [
        {imageUrl: "http://imageurlsite.com/pdq"},
        {imageUrl: "http://imageurlsite.com/lol"},
        {imageUrl: "http://imageurlsite.com/zomg"}
    ]
}

With the MongoDB Aggregation Pipeline, how can I create a new array field from image and additionalImages without including the imageUrl part? I want the new field like this:

[
    "http://imageurlsite.com/xyz", 
    "http://imageurlsite.com/pdq",
    "http://imageurlsite.com/lol",
    "http://imageurlsite.com/zomg"
]

I tried using the following in the $group stage, which partly works, but I just want the string values.

{
  image: {$addToSet: "$image"},
  additionalImages: {$addToSet: "$additionalImages"}
}

Unfortunately, the result of the above gives me this;

[
    {imageUrl: "http://imageurlsite.com/xyz"}, 
    {imageUrl: "http://imageurlsite.com/pdq"},
    {imageUrl: "http://imageurlsite.com/lol"},
    {imageUrl: "http://imageurlsite.com/zomg"}
]

Upvotes: 0

Views: 1425

Answers (1)

Demo - https://mongoplayground.net/p/KOSCPLetrZO

db.collection.aggregate([
  {
    $group: {
      _id: null,
      image: { $addToSet: "$image.imageUrl" }, // take imageUrl 
      additionalImages: { $addToSet: "$additionalImages.imageUrl" } // take imageUrl
    }
  },
  {
    $set: {
      images: {
        "$concatArrays": [ // combine both arrays
          { "$first": "$additionalImages" },
          "$image"
        ]
      }
    }
  },
  {
    "$project": { images: 1 } // project only images
  }
])

Output -

[
  {
    "_id": null,
    "images": [
      "http://imageurlsite.com/pdq",
      "http://imageurlsite.com/lol",
      "http://imageurlsite.com/zomg",
      "http://imageurlsite.com/xyz"
    ]
  }
]

Upvotes: 2

Related Questions