Grouping data by Ignition field values

I want to group the data based on the values of the “ignition” field. If the “ignition” value is 1, all records with the value 1 should be grouped together until the next value of 0 is encountered, and so on.

I have 86400 records in MongoDB, and I want to query the data to achieve the desired output.

[
  {
    ignition: 1,
    time: 112        
  },
  {
    ignition: 1,
    time: 193        
  },     
  {
    ignition: 0,
    time: 115        
  },
  {
    ignition: 1,
    time: 116        
  },
  {
    ignition: 1,
    time: 117        
  },
  {
    ignition: 1,
    time: 118        
  },
  {
    ignition: 0,
    time: 119        
  },
  {
    ignition: 1,
    time: 120        
  },
  {
    ignition: 1,
    time: 121        
  },
  {
    ignition: 1,
    time: 122        
  },
  {
    ignition: 0,
    time: 123        
  },
]

I want the output like this:


{
  time: [112,193],
  time: [116,117,118],
  time: [120,121,122]
}

Hi @Muhammad_Nabeel,

Welcome to the MongoDB Community forums :sparkles:

Can you clarify that the input document is a single document, or is it an array inside a document (and thus the example is one document)?

Also,

Your example output is not a valid document - You can’t have multiple fields with the same name.

However, considering the question, it’s complicated to group the data based on the values of the ignition field because the ordering of documents in MongoDB is not guaranteed unless you specify a sorting parameter explicitly. This can make it difficult to perform certain types of aggregations, such as grouping data based on the values of a particular field.

I suggest you perform the group operation in your application code after retrieving the data from MongoDB. You could iterate over the documents, keeping track of the current group of ignition values, and creating separate arrays for each group as you encounter them. Here is the JS code for your reference:

const data =[...];
const group = [];
let currentGroup = [];

data.forEach((document) => {
  if (document.ignition === 1) {
    currentGroup.push(document.time);
  } else if (currentGroup.length > 0) {
    group.push(currentGroup);
    currentGroup = [];
  }
});

if (currentGroup.length > 0) {
  group.push(currentGroup);
}
....

I hope it helps!

Thanks,
Kushagra