karnish
karnish

Reputation: 79

MySQL query equivalent in MongoDB

I am looking for help from someone who is expert on Mongodb Development. Below is My MySQL query :

select column_1,column_2,group_concat(column3 order by column4 asc ) as data_1 , group_concat(column5 order by column4 asc) as data_2 
from table_name 
where  column4>=DATE_SUB(NOW(),INTERVAL 15 MINUTE)
group by column_1,column_2

Basically I want data for past 15 minutes and group concat column data based on group by certain columns. Please help me get through this query.

Below is the sample data stored in Mongodb

{
    "_id" : ObjectId("6364fd1ae855d15c22632077"),
    "column3" : 1,
    "column_1" : 123456789,
    "column5" : "xyz",
    "source" : 1,
    "column_2" : NumberLong("22116755"),
    "column4" : ISODate("2022-11-04T11:51:55Z")
}

Upvotes: 0

Views: 329

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59456

Try this one:

db.collection.aggregate([
   { $match: { column4: { $gte: new Date(ISODate().getTime() - 1000 * 60 * 15) } } },
   { $sort: { column4: 1 } },
   {
      $group: {
         _id: { column_1: "$column_1", column_2: "$column_2" },
         data: { $push: { data_1: "$column3", data_2: "$column5" } },
      }
   },
   { $replaceWith: { $mergeObjects: ["$_id", "$data"] } }
])

Upvotes: 1

Related Questions