0

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"}
]

1 Answer 1

2

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"
    ]
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.