print data form List of Maps flutter/ - flutter

I need to print startTime form this Map of decodedData.
I am new to flutter .
I need startTime so that I can show the time slots for availability.
Map decodedData = { "sts" : "SUCCESS", "data" : [{
"startTime": 1665392445000,
"between": 1665414045000
},
{
"startTime": 1665414045000,
"between": 1665414045000
},
]};

List<String> arrayStartTime = (decodedData["data"] as List<Map<String,dynamic>>).map((e) => "${e['startTime']}").toList();
result:
[1665392445000, 1665414045000]
You can set array int or String type as per your requirement

You must try this :
decodedData["data"]).values.forEach((v) => print("startTime =
${v["startTime"]}"));

You can use decodedData[0]['startTime'] and so on, you can also use for loop.
and use
DateTime.fromMillisecondsSinceEpoch(decodedData[0]['startTime'],isUtc: true).toString() to print it or format it as per your need.

Try this:
Map decodedData = { "sts" : "SUCCESS", "data" : [{
"slotKey": "1665392445000_|_1665394245000",
"startTime": 1665392445000,
"endTime": 1665394245000,
"isbooked": true,
"bookedBy": "qxWESdGsHvhywe3S7FxDeO2"
},
{
"slotKey": "1665414045000_|_1665415845000",
"startTime": 1665414045000,
"endTime": 1665415845000,
"isbooked": false
},
]};
void main(){
for(var item in decodedData["data"]){
print("startTime = ${item["startTime"]}");
}
}

Related

Isn't it possible to concat new value to a field in MongoDB document while updating it?

I have few documents in a MongoDB Collection and each has a unique field called "requestid". Now I need to update a field "requeststatus" by concatenating a new value to an existing one in NodeJS application. I started using MongoDB for very recent and have less exposure in it's features.
After doing some research I got to know I could use "$set" with "$concat"
Updating with filter & options:
var filter = { requestid: data.requestid };
var updateDoc = { $set: { requeststatus: { $concat: ["$requeststatus","-",`. ${data.status}`] } } };
var options = { multi: true };
var jobDetails = { filter, updateDoc, options };
NodeJS code:
async function updateJobDetails(connection, data, mongoDetails){
const result = await connection.db(mongoDetails.mongoDatabase).collection(mongoDetails.collection).updateOne(data.filter, data.updateDoc, data.options);
}
This is not doing as expected, instead it's adding the new concatenated value as array of Object into MongoDB collection.
Existing document:
{
"_id": {
"$oid": "6307120d3oiu895oi9e82eea5"
},
"requestid": "123456789",
"iscancelled": true,
"organizationid": "3",
"instanceid": "172",
"offerid": "offer123",
"promotionid": "promo123",
"jobtype": "portaljob123",
"jobid": "job123",
"requeststatus": "began"
}
Updated document:
{
"_id": {
"$oid": "6307120d3oiu895oi9e82eea5"
},
"requestid": "123456789",
"iscancelled": true,
"organizationid": "3",
"instanceid": "172",
"offerid": "offer123",
"promotionid": "promo123",
"jobtype": "portaljob123",
"jobid": "job123",
"requeststatus": {
"$concat": ["$requeststatus", "-", "tigger_datalink stopped since request was cancelled"]
}
}
Is there anything that I am doing wrong here? I even tried updateMany() but of no use. Run it as many times as desired it won't concat but keep updating same value as Object Any help is appreciated here.
(Working) Updated NodeJS code:
async function updateJobDetails(connection, data, mongoDetails){
const result = await connection.db(mongoDetails.mongoDatabase).collection(mongoDetails.collection).updateOne(data.filter, [data.updateDoc], data.options);
}
In order to use an existing field's data you need to use an update with a pipeline.
Try using your updateDoc inside a pipeline, like this:
var filter = { requestid: data.requestid };
var updateDoc = { $set: { requeststatus: { $concat: ["$requeststatus","-",`. ${data.status}`] } } };
var options = { multi: true };
var jobDetails = { filter, [updateDoc], options };
See how it works on the playground example

How to sort a List of items based on dateTime in Flutter | Flutter

I have List of products with product name and date. I want to sort that list of items based on date and time. This is the list of items that i want to sort,
List items = [
{
"productName":"Icecream",
"date":"2019-10-17 10:06:12.278"
},
{
"productName":"Juice",
"date":"2021-09-20 19:08:16.274"
},
{
"productName":"Rice",
"date":"2020-05-13 08:02:16.177"
},
{
"productName":"Cheese",
"date":"2021-10-23 20:02:16.254"
},
{
"productName":"Sugar",
"date":"2019-11-22 00:00:00.000"
},
];
This is the Expected Output what i want,
List sortedList = [
{
"productName":"Icecream",
"date":"2019-10-17 10:06:12.278"
},
{
"productName":"Sugar",
"date":"2019-11-22 00:00:00.000"
},
{
"productName":"Rice",
"date":"2020-05-13 08:02:16.177"
},
{
"productName":"Juice",
"date":"2021-09-20 19:08:16.274"
},
{
"productName":"Cheese",
"date":"2021-10-23 20:02:16.254"
},
];
This is a simple code using the build-in function .compareTo that can help you out:
void main() async {
List items = [
{"productName": "Icecream", "date": "2019-10-17 10:06:12.278"},
{"productName": "Juice", "date": "2021-09-20 19:08:16.274"},
{"productName": "Rice", "date": "2020-05-13 08:02:16.177"},
{"productName": "Cheese", "date": "2021-10-23 20:02:16.254"},
{"productName": "Sugar", "date": "2019-11-22 00:00:00.000"},
];
// You can change the position of `a` and `b` to get a reversed result
// as well
items.sort((a, b) => a['date'].compareTo(b['date']));
print(items);
}
you can use compareTo method in list to compare results based on these results you can sort list using .sort method on list

How to convert the JSON response to Map in Flutter

I have a JSON response from my API call. The format is like this.
[
{
"hotelname": "A",
"roomno": "101",
"occupancy": "4"
},
{
"hotelname": "A",
"roomno": "102",
"occupancy": "3"
},
{
"hotelname": "B",
"roomno": "101",
"occupancy": "4"
},
{
"hotelname": "B",
"roomno": "202",
"occupancy": "3"
}
]
I want to write a code where in one dropdown list displays the names of the hotels(A,B,C etc) the other dropdown should display the corresponding roomno.
To achieve this i would like to convert my JSON response to a MAP like the below.
Map<String,String> _hoteldata = {
"101":"A",
"102":"A",
"101":"B",
"202":"B",
};
First, you parse the json using jsonDecode(), then create a map from the list, for example, using Map.fromEntries():
import 'dart:convert';
var rooms = jsonDecode(json) as List;
var hotelData = Map.fromEntries(
rooms.map((room) => MapEntry(room['roomno'], room['hotelname']))
);

Filter ResultSet after MongDB MapReduce

Consider the following MongoDB collection / prototype that keeps track of how many cookies a given person has at a given point in time:
{
"_id": ObjectId("5c5b5c1865e463c5b6a5b748"),
"person": "Drew",
"cookies": 1,
"timestamp": ISODate("2019-02-05T20:34:48.922Z")
}
{
"_id": ObjectId("5c5b5c2265e463c5b6a5b749"),
"person": "Max",
"cookies": 3,
"timestamp": ISODate("2019-02-06T20:34:48.922Z")
}
{
"_id": ObjectId("5c5b5c2e65e463c5b6a5b74a"),
"person": "Max",
"cookies": 0,
"timestamp": ISODate("2019-02-07T20:34:48.922Z")
}
Ultimately, I need to get all people who currently have more than 0 cookies - In the above example, only "Drew" would qualify - ("Max" had 3, but later only had 0).
I've written the following map / reduce functions to sort this out..
var map = function(){
emit(this.person, {'timestamp' : this.timestamp, 'cookies': this.cookies})
}
var reduce = function(person, cookies){
let latestCookie = cookies.sort(function(a,b){
if(a.timestamp > b.timestamp){
return -1;
} else if(a.timestamp < b.timestamp){
return 1
} else {
return 0;
}
})[0];
return {
'timestamp' : latestCookie.timestamp,
'cookies' : latestCookie.cookies
};
}
This works fine and I get the following resultSet:
db.cookies.mapReduce(map, reduce, {out:{inline:1}})
...
"results": [
{
"_id": "Drew",
"value": {
"timestamp": ISODate("2019-02-05T20:34:48.922Z"),
"cookies": 1
}
},
{
"_id": "Max",
"value": {
"timestamp": ISODate("2019-02-07T20:34:48.922Z"),
"cookies": 0
}
}
],
...
Max is included in the results - But I'd like for him to not be included (he has 0 cookies after all)
What are my options here? I'm still relatively new to MongoDB. I have looked at finalize as well as creating a temporary collection ({out: "temp.cookies"}) but I'm just curious if there's an easier option or parameter I am overlooking.
Am I crazy for using MapReduce to solve this problem? The actual workload behind this scenario will include millions of rows..
Thanks in advance

Find all objects, that's nested properties have desired value

I have collection with the following (sample) documents:
{
"label": "Tree",
"properties": {
"height": {
"type": "int",
"label": "Height",
"description": "In meters"
},
"coordinates": {
"type": "coords",
"label": "Coordinates"
},
"age": {
"type": "int",
"label": "Age"
}
}
}
Keys in the properties attribute are different for almost each of the documents in collection.
I want to find all documents that have at least one property of given type.
What I'm looking for is to query this for {"properties.*.type": "coords"}. But this is not working as it is only my invention of mongo query.
Every help I was able to find concerned the $elemMatch operator which I can not use here because properties is an object, not an array.
Hi as per my knowledge in mongodb not provide this kind of search. So for finding this first I separated out all keys using map-reduce and then find query form so below code will help you
var mapReduce = db.runCommand({
"mapreduce": "collectionName",
"map": function() {
for (var key in this.properties) {
emit(key, null);
}
},
"reduce": function(key, stuff) {
return null;
},
"out": "collectionName" + "_keys"
})
db[mapReduce.result].distinct("_id").forEach(function(data) {
findkey = [];
findkey.push("properties." + data + ".type");
var query = {};
query[findkey] = "coords";
var myCursor = db.collectionName.find(query);
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
})
MongoDB doesn't support searches on keys - things like properties.* to match all subkeys of properties, etc. You shouldn't have arbitrary keys or keys that you don't know about in your schema, unless they are just for display, generally, because you will not be able to interact with them very easily in MongoDB.
If you do want to store dynamic attributes, the best approach is usually an array like the following:
{
"properties" : [
{
"key" : "height",
"value" : {
"type" : "Int",
"label" : "Height",
"description" : "In meters"
}
},
...
]
}
Efficient querying for your use case
find all documents that have at least one property of given type
results from an index on { "key" : 1 }:
db.test.find({ "properties.key" : { "$in" : ["height", "coordinates", "age"] } })