0

I would like to join two Arrays from one collection based on the array index, not a (primary) key.

The Data looks like this:

{"_id" : ObjectId("1"),
    "clicks" : {
        "cumulative" : {
            "data" : [
                3,
                7,
                8
            ]
        },
        "daily" : {
            "data" : [
                3,
                4,
                1
            ]
        }
    },
    "websiteId" : "abcdef"
    "day" : {
        "isoDate" : [
            ISODate("2016-07-07T02:00:00.000+02:00"),
            ISODate("2016-07-08T02:00:00.000+02:00"),
            ISODate("2016-07-09T02:00:00.000+02:00")
            ]}
    },
....

I would like to join day.isoDate with clicks.cumulative.data based on the index of each array. The table then should look like this:

  ObjectID   Date         Clicks
    1          2016-07-07   3
    1          2016-07-08   7
    1          2016-07-09   8

What I tried so far:

db.collection1.aggregate([  
  {$unwind: "$day.isoDate"},
  {$match: {"websiteId": "abcdef"} },
  {$group: {_id: "$day.isoDate.Value"}}
])

Does anybody have a suggestion?

1 Answer 1

1

This can be achieved by telling mongodb to store the index of the unwinded array an then use it within a projection:

db.test.aggregate([  
    {"$unwind": {
      path: "$day.isoDate",
      includeArrayIndex: "index"
    }},
    {"$project": {
        "Date" : "$day.isoDate",
        "Clicks": {
            "$arrayElemAt" : [
                "$clicks.cumulative.data",
                "$index"
            ]
        }}
    }])

This will output

{ "_id" : ObjectId("5910de2e92842f684b605965"), "Date" : ISODate("2016-07-07T00:00:00Z"), "Clicks" : 3 }
{ "_id" : ObjectId("5910de2e92842f684b605965"), "Date" : ISODate("2016-07-08T00:00:00Z"), "Clicks" : 7 }
{ "_id" : ObjectId("5910de2e92842f684b605965"), "Date" : ISODate("2016-07-09T00:00:00Z"), "Clicks" : 8 }
>
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thank you very much.

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.