1

Explanation: how we can do the group based on array elements, I want to do a group based on 0 element of both arrays.

{ "st": [ [ "2011-01-04T12:18:41Z", 0 ], [ "2011-01-04T15:00:00Z", 0 ] ], "en": [ [ "2011-01-04T14:59:50Z", 1 ], [ "2011-01-04T15:05:00Z", 4 ] ] } 

The expected output document looks like. for example

[ { "st": "2011-01-04T12:18:41Z", "en": "2011-01-04T14:59:50Z", "st_val": 0, "en_val": 1, "total_index_count": 2 }, { "st": "2011-01-04T15:00:00Z", "en": "2011-01-04T15:05:00Z", "st_val": 0, "en_val": 4, "total_index_count": 2 } ] 
3
  • can you add another more complex example? i'm not sure i understand. do you want to just match index i in st with index i in en arrays? Commented Sep 13, 2021 at 11:50
  • yes, I want to combine them both index i as one document. Commented Sep 13, 2021 at 11:52
  • Its very similar to this map on indexes and merge objects. Commented Sep 13, 2021 at 12:01

1 Answer 1

1

You can do this in several different ways, here is an approach utilizing the $map and $arrayElemAt operators.

db.collection.aggregate([ { "$project": { elements: { $map: { input: { $range: [ 0, { $size: "$st" } ] }, in: { st_val: { "$arrayElemAt": [ { "$arrayElemAt": [ "$st", "$$this" ] }, 0 ] }, st: { "$arrayElemAt": [ { "$arrayElemAt": [ "$st", "$$this" ] }, 1 ] }, en_val: { "$arrayElemAt": [ { "$arrayElemAt": [ "$en", "$$this" ] }, 0 ] }, en: { "$arrayElemAt": [ { "$arrayElemAt": [ "$en", "$$this" ] }, 1 ] }, } } } } }, { $unwind: "$elements" }, { $replaceRoot: { newRoot: "$elements" } } ]) 

Mongo Playground

Sign up to request clarification or add additional context in comments.

7 Comments

Its look fine, I have 2 questions. 1. in the project stage how we can count the index of the array total_index_count is missing. 2. In ` "$range":[0,{ "$size": "$st"}] ` why you took st why not en
the assumption is they are both the same length, if not you should specify the behavior your expecting.
and i wasn't sure what total_index_count is because they are both 2 in the result you specified.
st and en both index always be equal. for example, if st has 2 indexes, en should be 2 indexes, so how we can count the index at the project stage is it then we need the group stage?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.