I have 1000 Documents in one of the collection.
{ "_id": ObjectId("56d97671f6ad671b7d1c3d76"), "parseId":
"TdKxj9FFPY", "phone": "6643545645", "dob": "15-06-87", "age": 121
"createdAt": ISODate("2016-03-01T16:39:00.947Z"), "updatedAt":
ISODate("2016-03-01T16:39:00.947Z"), "__v": 0 }
{ "_id":ObjectId("56d97671f6ad671b7d1c3d76"), "parseId": "TdKxj9FFPY",
"phone": "9847523654", "dob": "15-06-93", "age": 100 "createdAt":
ISODate("2016-03-01T16:39:00.947Z"), "updatedAt":
ISODate("2016-03-01T16:39:00.947Z"), "__v": 0 }
{ "_id":ObjectId("56d97671f6ad671b7d1c3d76"), "parseId": "TdKxj9FFPY",
"phone": "4564646646", "dob": "15-06-43", "age": 152 "createdAt":
ISODate("2016-03-01T16:39:00.947Z"), "updatedAt":
ISODate("2016-03-01T16:39:00.947Z"), "__v": 0 }
...................
...................
But some of the values of age are wrong.The Values of dob are right.So i need to update the values of age based on the dob in a single query manually?
Finally i found a solution.I just export the collection in to a json file and updated all the documents by using js function and import the collections in to the db.
html
<html>
<head>
<script type="text/javascript" src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<button id="save">save</button>
</body>
<script type="text/javascript">
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
var exportData;
$.getJSON("input.json", function(data) {
exportData = data;
exportData.forEach(function(item, index) {
// console.log('item dob', item.dob);
var dobInfo = item.dob.split('-');
var dd = dobInfo[0];
if (dd < 10) {
dd = '0' + dd;
}
var mm = dobInfo[1];
if (mm < 10) {
mm = '0' + mm;
}
var yy = dobInfo[2];
yy = (yy < 17) ? '20' + yy : '19' + yy;
// console.log('dd', dd);
// console.log('mm', mm);
// console.log('yy', yy);
var newdate = mm + '-' + dd + '-' + yy;
// console.log('newdate',newdate);
console.log('index[' + index + ']', item.dob);
var age = getAge(newdate);
console.log('age--->', age);
exportData[index].age = age;
});
});
document.getElementById('save').onclick = function() {
var textToSave = JSON.stringify(exportData),
filename = 'output.json',
blob = new Blob([textToSave], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, filename);
}
</script>
</html>
EDITED: my bad about the first one.
Export your data to a JSON and run it through this and reimport it. Your only dependency is fs and momentjs.
var moment = require('moment'),
fs = require('fs'),
json = [
{ "_id":"56d97671f6ad671b7d1c3d76", "parseId": "TdKxj9FFPY", "phone": "6643545645", "dob": "15-06-87", "age": 121, "createdAt": "2016-03-01T16:39:00.947Z", "updatedAt": "2016-03-01T16:39:00.947Z", "__v": 0 },
{ "_id":"56d97671f6ad671b7d1c3d76", "parseId": "TdKxj9FFPY", "phone": "9847523654", "dob": "15-06-93", "age": 100, "createdAt": "2016-03-01T16:39:00.947Z", "updatedAt": "2016-03-01T16:39:00.947Z", "__v": 0 },
{ "_id":"56d97671f6ad671b7d1c3d76", "parseId": "TdKxj9FFPY", "phone": "4564646646", "dob": "15-06-43", "age": 152, "createdAt": "2016-03-01T16:39:00.947Z", "updatedAt": "2016-03-01T16:39:00.947Z", "__v": 0 }
];
Object.keys(json).forEach(function(key) {
age = moment().diff(moment(json[key].dob,"DD/MM/YY"),'years');
//
//dates before 1970 are negative
//
if (parseInt(age) < 0) {
age += 100;
}
json[key].age = age;
});
fs.writeFile('data.json', JSON.stringify(json), function (err) {
if (err) return console.log(err);
console.log('compeleted');
});
age outputs = [29, 23, 74];
Related
I have a application submitting portal, I which user his/her request. the issue I am facing is to separate data on base created at field which separates data from current month to past 12 months.
The Data format is like this.
[
{
"_id": "63b3fca07d1f15f5d33e12e0",
"first_name": "ZANAEN",
"last_name": "Ullah",
"date_of_birth": "03/12/2002",
"cnic_number": "55555-5555555-5",
"expiry_date": "10/01/2027",
"current_address": "Qqqq",
"current_city": "Bhawalpur",
"permanent_address": "1111",
"permanent_city": "Bhawalpur",
"mobile_number": "0000-0000000",
"loan_ammount": "5000",
"purpose_of_loan": "Micro-Enterprices",
"current_occupation": "Job",
"nature_of_business": "Existing",
"duration_of_business": "5 years",
"business_address": "11111",
"business_city": "Bhawalpur",
"createdAt": "2022-01-03T10:00:00.562Z",
"updatedAt": "2022-01-03T10:00:00.562Z",
"applicationId": 22121022,
"__v": 0
},
]
and the function is like
getChartLast1Year(objects) {
const monthCounts = [];
const currentMonth = moment().month();
const currentYear = moment().year();
for (let i = 0; i < 12; i++) {
const month = (currentMonth + i) % 12;
const year = month < currentMonth ? currentYear - 1 : currentYear;
const monthData = objects.filter((application) => {
const createdAt = moment(application.createdAt);
return createdAt.month() === month && createdAt.year() === year;
});
monthCounts.push({
month: moment().month(month).format("MMM"),
year: moment().year(year).format("YYYY"),
count: monthData.length,
});
}
console.log("monthCounts", monthCounts);
return monthCounts;
},
If anyone can help I would be so thankful
I want to scan dynamodb using filter on product_id showing in below json of table.
Can anybody explain how to do scanning using filter of product_id.
Wants to scan dynamodb table data using documentclient.
Wants to find all fields which has product_id: something
{
"mandi_id": 1,
"product": [
{
"updated_price": 24,
"product_id": 2,
"last_price": 23
},
{
"updated_price": 24,
"product_id": 5,
"last_price": 23
}
],
"status": "active",
"createdAt": "2022-04-21T08:23:41.774Z",
"mandiCloseTime": "4pm",
"mandi_description": "anaj mandi",
"mandi_name": "gaziabad anaj mandi",
"state": "uttar pradesh",
"city": "gaziabad",
"main_image_s3": "",
"mandi_latlong": {
"lng": 77.48325609999999,
"lat": 28.680346
},
"mandiOpenTime": "10am",
"updatedAt": "2022-04-21T08:23:41.774Z",
"address_name": "gavindpuram",
"landmark_name": "mandi",
"village": "gaziabad",
"postal": "201013"
}
I have tried the following set of code but it is returning empty array list
var params = {
TableName: "dev-agrowave-mandi-management",
// Select: "ALL_ATTRIBUTES"
FilterExpression: "contains(#product,:product)",
ExpressionAttributeNames: {
"#product": "product",
},
ExpressionAttributeValues: { ":product": {"product_id":parseInt(id)}
}
};
let lastEvaluatedKey = 'dummy'; // string must not be empty
const itemsAll = [];
while (lastEvaluatedKey) {
const data = await docClient.scan(params).promise();
itemsAll.push(...data.Items);
lastEvaluatedKey = data.LastEvaluatedKey;
if (lastEvaluatedKey) {
params['ExclusiveStartKey'] = lastEvaluatedKey;
}
}
return {msg:itemsAll,params:params};
I want to remove square bracket "[ ]" in json object or concatenate some array of object to one array of object.
This code for counting current stock
currentStock : ( req, res, next) => {
var listed_item = _(arr_items).map( (z) => {
var result = module.exports.getTransactionAfterDate(z.created_at, z.item_id);
return result;
})
var jsonContent = JSON.stringify(listed_item);
return res.send(jsonContent);
},
getTransactionAfterDate : (date, item_id) => {
var result = _(db_transaction).filter( (x) => {
return x.created_at > date && x.item_id == item_id;
});
return result;
}
this is "listed_item" json result
[
[{
"id": 30608,
"item_id": "A01001",
"quantity": 150,
"status": "OUT",
"created_at": "2020-02-10 16:11:51",
}],
[],
[{
"id": 30412,
"item_id": "A02001",
"quantity": 53,
"status": "OUT",
"created_at": "2020-02-06 14:44:20",
}, {
"id": 30482,
"item_id": "A02001",
"quantity": 33,
"created_at": "2020-02-07 15:26:50",
"updated_at": "2020-02-07 15:26:50",
}]
]
what i want is like this
[
{
"id": 30608,
"item_id": "A01001",
"quantity": 150,
"status": "OUT",
"created_at": "2020-02-10 16:11:51",
},
{
"id": 30412,
"item_id": "A02001",
"quantity": 53,
"status": "OUT",
"created_at": "2020-02-06 14:44:20",
}, {
"id": 30482,
"item_id": "A02001",
"quantity": 33,
"created_at": "2020-02-07 15:26:50",
"updated_at": "2020-02-07 15:26:50",
}
]
note
i tried concatenate "getTransactionAfterDate" inside "arr_items" map to join all array inside
var temp = [];
var listed_item = _(arr_items).map( (z) => {
temp = _(temp).concat(module.exports.getTransactionAfterDate(z.created_at, z.item_id));
var result = temp;
return result;
})
but the result is empty array
[ [], [], [] ]
Try this
currentStock : ( req, res, next) => {
var items = [];
_(arr_items).forEach( (z) => {
var result = module.exports.getTransactionAfterDate(z.created_at, z.item_id);
result.forEach( item => {
items.push(item);
}
})
var jsonContent = JSON.stringify(items);
return res.send(jsonContent);
},
You can 'flatten' the array with lodash, which will just merge all the arrays into a single one:
_(arr).flatten()
That should then give you a single array of your objects, with no empty arrays either.
.flatten() in the lodash docs here: https://lodash.com/docs/#flatten
So it would be something like this (edited based on comments):
currentStock : ( req, res, next) => {
var listed_item = _(arr_items).map( (z) => {
var result = module.exports.getTransactionAfterDate(z.created_at, z.item_id);
return result;
})
var flattened = _(listed_item).flatten();
var jsonContent = JSON.stringify(flattened);
return res.send(jsonContent);
},
Nice and simple! (if I correctly understood what you are trying to do :-)
this can be done with the combination of _.flatten (for this lodash is required) and Array.prototype.filter like shown below
let newArray = _.flatten(listed_item.filter(e => e.length > 0))
i am getting data list from controller to ajax function to my datatable.all works well but my question is, I want to get one of list property to textbox and other values to datatable columns.for example:
list= TotalAMount,PAidAmount,RemAmount
and datatable
Totalamount| PaidAMount | RemAmount| ---------??
20 | 4 | 16 |
so this works fine but i want to get TotalAmount value to some textbox also like textbox=20.
my JS function==>>
`
function AddGetHistoryView(SupplierID) {
$('#HistoryModal').modal('show');
Datatabless = $("#HistoryTable").DataTable({
"autoWidth": false,
"ajax": {
"type": "GET",
"url": "#Url.Action("getHistoryData", "Supplier")/" + SupplierID,
"datatype": "JSON",
data: {
"Amount": $("#TotalAmount").val()
},
data: { SupplierID: SupplierID },
},
"columns": [
{
"data": "DetailID",
"visible": false,
},
{
"data": "TotalAmount",
"width": "5%",
},
{
"data": "PaidAmount",
"width": "5%",
},
{
"data": "RemAmount",
"width": "5%",
},
{
"data": "PaidDate",
"width": "5%",
},
{
"data": "PaymentType",
"width": "5%",
},
{
"data": "DetailID", "render": function (data) {
return "<a class='btn btn-success' onclick=EditRow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-edit'> Update</i><a/>,<a class='btn btn-danger' onclick=deleteRow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-trash'> Delete</i> <a/>";
},
"width": "40%",
"orderable": false,
"pagingType": "full_numbers",
"paging": true,
},
],
});
}
`
Controller Method==>
public ActionResult getHistoryData(int SupplierID)
{
ob.Configuration.ProxyCreationEnabled = false;
var data = ob.Table_Supplier.Join(ob.Table_SupplierDetails, sup => sup.SupplierID, det => det.SupplierID, (sup, det) => new
{
DetailID=det.DetailID,
SupplierID = sup.SupplierID,
TotalAmount = det.TotalAmount,
RemAmount = det.RemAmount,
PaidAmount = det.PaidAmount,
PaidDate = det.PaidDate,
PaymentType = det.PaymentType,
Amount = sup.Amount
}).Where(x=>x.SupplierID==SupplierID).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}
I am trying to get count of unseen messages from object in lodash.
below is my object
[
"conversation_id": "5a88779b2321141f2864e484"
"messages": [
{
"message_id": "5a88779b2321141f2864e483",
"sender_uid": 2,
"receiver_uid": 1,
"created": "2018-02-17T18:42:35.252Z",
"status": 1,
"delivered": false,
"seen": true,
}
]
]
I want to get count of seen: false messages
You can use filter to get all see = false messages and then can check length
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
var unseen_messages = _.filter(users.messages, message => { return !message.seen; }).length;
console.log(unseen_messages);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Without lodash you can use reduce
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
items = users.messages;
var totalCount = items.reduce((total, obj) => { return (!obj.seen) ? (total +1) : total }, 0);
console.log(totalCount);
_.sumBy would do the trick
const unseenMessages = _.sumBy(users.messages, message => message.seen === false);