Move "property: value" position in MongoDB - database

I've been wondering if you could move one field position. For example:
Current Document:
{
user_id: 1234567890,
coins: 100,
card: 500,
username: 'Shin'
}
(Expected Document) I would like to move the username into this:
{
user_id: 1234567890,
username: 'Shin',
coins: 100,
card: 500
}

Query
as far as i know project keeps the order we define
but try it on your driver to be sure, with more fields also
the problem is that we have to do this for all fields (here are only 4 so its ok)
but why you need that? in general because its hash-map we dont care about the order
Playmongo
aggregate(
[{"$project":
{"user_id": "$user_id",
"username": "$username",
"coins": "$coins",
"card": "$card"}}])

Related

Is there a way of reading from sub arrays?

I am currently building an iOS application that stores user added products using Google Firestore. Each product that is added is concatenated into a single, user specific "products" array (as shown below - despite having separate numbers they are part of the same array but separated in the UI by Google to show each individual sub-array more clearly)
I use the following syntax to return the data from the first sub-array of the "products" field in the database
let group_array = document["product"] as? [String] ?? [""]
if (group_array.count) == 1 {
let productName1 = group_array.first ?? "No data to display :("`
self.tableViewData =
[cellData(opened: false, title: "Item 1", sectionData: [productName1])]
}
It is returned in the following format:
Product Name: 1, Listing Price: 3, A brief description: 4, Product URL: 2, Listing active until: 21/04/2021 10:22:17
However I am trying to query each of the individual sections of this sub array, so for example, I can return "Product Name: 1" instead of the whole sub-array. As let productName1 = group_array.first is used to return the first sub-array, I have tried let productName1 = group_array.first[0] to try and return the first value in this sub-array however I receive the following error:
Cannot infer contextual base in reference to member 'first'
So my question is, referring to the image from my database (at the top of my question), if I wanted to just return "Product Name: 1" from the example sub-array, is this possible and if so, how would I extract it?
I would reconsider storing the products as long strings that need to be parsed out because I suspect there are more efficient, and less error-prone, patterns. However, this pattern is how JSON works so if this is how you want to organize product data, let's go with it and solve your problem.
let productRaw = "Product Name: 1, Listing Price: 3, A brief description: 4, Product URL: 2, Listing active until: 21/04/2021 10:22:17"
First thing you can do is parse the string into an array of components:
let componentsRaw = productRaw.components(separatedBy: ", ")
The result:
["Product Name: 1", "Listing Price: 3", "A brief description: 4", "Product URL: 2", "Listing active until: 21/04/2021 10:22:17"]
Then you can search this array using substrings but for efficiency, let's translate it into a dictionary for easier access:
var product = [String: String]()
for component in componentsRaw {
let keyVal = component.components(separatedBy: ": ")
product[keyVal[0]] = keyVal[1]
}
The result:
["Listing active until": "21/04/2021 10:22:17", "A brief description": "4", "Product Name": "1", "Product URL": "2", "Listing Price": "3"]
And then simply find the product by its key:
if let productName = product["Product Name"] {
print(productName)
} else {
print("not found")
}
There are lots of caveats here. The product string must always be uniform in that commas and colons must always adhere to this strict formatting. If product names have colons and commas, this will not work. You can modify this to handle those cases but it could turn into a bowl of spaghetti pretty quickly, which is also why I suggest going with a different data pattern altogether. You can also explore other methods of translating the array into a dictionary such as with reduce or grouping but there are big-O performance warnings. But this would be a good starting point if this is the road you want to go down.
All that said, if you truly want to use this data pattern, consider adding a delimiter to the product string. For example, a custom delimiter would greatly reduce the need for handling edge cases:
let productRaw = "Product Name: 1**Listing Price: 3**A brief description: 4**Product URL: 2**Listing active until: 21/04/2021 10:22:17"
With a delimiter like **, the values can contain commas without worry. But for complete safety (and efficiency), I would add a second delimiter so that values can contain commas or colons:
let productRaw = "name$$1**price$$3**description$$4**url$$2**expy$$21/04/2021 10:22:17"
With this string, you can much more safely parse the components by ** and the value from the key by $$. And it would look something like this:
let productRaw = "name$$1**price$$3**description$$4**url$$2**expy$$21/04/2021 10:22:17"
let componentsRaw = productRaw.components(separatedBy: "**")
var product = [String: String]()
for component in componentsRaw {
let keyVal = component.components(separatedBy: "$$")
product[keyVal[0]] = keyVal[1]
}
if let productName = product["name"] {
print(productName)
} else {
print("not found")
}

How to choose one data from an array without random

I want to ask about how I can select one data from the array, and choose another without using a random function?
{
no: 1,
id_pertanyaan: "9",
pertanyaan: "Alat indra yang paling peka untuk membedakan benda panas dan benda dingin adalah?",
point: "1",
pilA: "Hidung",
pilB: "Telinga",
pilC: "Kulit",
cabang: "IPA",
jawaban: "Kulit",
keterangan: "Alat indra yang paling peka untuk membedakan benda panas dan benda dingin adalah?"
},
{
no: 2,
id_pertanyaan: "11",
pertanyaan: "Zat hijau daun disebut juga dengan?",
point: "1",
pilA: "Floem",
pilB: "Klorofil",
pilC: "Xylem",
cabang: "IPA",
jawaban: "Klorofil",
keterangan: "Zat hijau daun disebut juga dengan?"
},
And this is my function
//console.log(this.state.gagec);
var item = this.state.pertanyaande[
Math.floor(Math.random() * this.state.pertanyaande.length)
];
this.setState(
{
id_pertanyaan: item.id_pertanyaan,
pertanyaan: item.pertanyaan,
point: item.point,
pilA: item.pilA,
pilB: item.pilB,
pilC: item.pilC,
jawaban: item.jawaban,
keterangan: item.keterangan,
},
() => {
this.setTimer();
}
);
The code above is I try to be able to get the array randomly, but it raises new problems because sometimes the same data appears, I want to display data from the array only one data (not all) in a way one by one, how to get the first data in my array, then I run the script again I get the second array data?
I just had to make it not random and change it to state so if id 1 is active then if the function rerun it'll get id 2 because state+1

dataweave filter and maxBy on nested array list

I have a list of students and their marks for respective subjects. I want to filter all students of a specific grades and then find the student who got maximum marks in a specific object.
[
{
"name": "User 01",
"grade": 1,
"schoolName": "school01",
"marks": {
"english": 10,
"math": 30,
"social": 30
}
},
{
"name": "User 02",
"grade": 1,
"schoolName": "school02",
"marks": {
"english": 10,
"math": 20,
"social": 30
}
}
]
I am able to perform both the operations independently. can someone help me find the student object who got max marks in math in a specific grade.
If I understand your requirement correctly this script does it. Just change the variables grade and topic to the specific values you are interested in.
Generally speaking it is always better to provide example outputs and whatever you got as script to understand better the context, in addition to the input samples.
%dw 2.0
output application/json
var grade = 1
var topic = "math"
---
flatten(
payload map (alumn, order) ->
(alumn.marks pluck ((value, key, index) ->
{
name: alumn.name,
grade: alumn.grade,
result:value,
topic: key
})
)
) // restructure the list to one result per element
filter ((item, index) -> (item.grade == grade)) // filter by grade
maxBy ((item) -> item.result) // get the maximum result
I used it below to achieve it.
%dw 2.0
output application/json
var grade = 1
var topic = "math"
---
payload filter (
((item, index) -> item.grade == grade)
) maxBy ($.marks.math as String {format: "000000"})

How to build comment reply structure using reactjs?

I am working on react js application and building comment reply structure. API is returning me an array of comments, but it's not in a comment hierarchy.
My API response is like this:
review: {_id: 35,email: "test#gmail.com", review: "Shavon B does an AMAZING job!! I had another fant…e taking care of my home. Shavon is a rock star!"}
comments: [
0: {_id: 36, status: 1, email: "neha#shandil.com", review: "Shavon B does an AMAZING job!! I had another fant…e taking care of my home. Shavon is a rock star!", parent_id: 35, reply_to:35}
1: {_id: 37, status: 1, email: "archana#gmail.com", review: " Thank you for sharing your review of your home cl…e taking care of my home. Shavon is a rock star!", parent_id: 35, reply_to:36}
2: {_id: 39, status: 1, email: "radhika#dummy-url.com", review: "Shavon B does an AMAZING job!! I had another fant…e taking care of my home. Shavon is a rock star!", parent_id: 35, reply_to:37}
3: {_id: 40, status: 1, email: "archi#123.com", review: "good", parent_id: 35, reply_to:36}
4: {_id: 41, status: 1, email: "test#test.com", review: "Testing", parent_id: 35, reply_to:35}
]
here parent_id means these are comments for any blog with id 35, and reply_to means this is a reply for that particular comment _id, like array at index 1 is a reply for comment at 0 index.
Now I am also getting a new reply at the end of the list. Now I want to show all comments in their hierarchy.
Now the problem is I am getting a simple array with all comments and replies, how can I show them in the hierarchy.
Is this possible to push HTML in between, please suggest me a solution, I want to show comments up to two levels.
You will need to convert comments to tree structure and will need to write recursive logic to process comments.
Function for converting flat list to the tree:
function unflatten(arr) {
var tree = [],
mappedArr = {},
arrElem,
mappedElem;
// First map the nodes of the array to an object -> create a hash table.
for(var i = 0, len = arr.length; i < len; i++) {
arrElem = arr[i];
mappedArr[arrElem._id] = arrElem;
mappedArr[arrElem._id]['children'] = [];
}
for (var id in mappedArr) {
if (mappedArr.hasOwnProperty(id)) {
mappedElem = mappedArr[id];
// If the element is not at the root level, add it to its parent array of children.
if (mappedElem.parent_id) {
mappedArr[mappedElem['parent_id']]['children'].push(mappedElem);
}
// If the element is at the root level, add it to first level elements array.
else {
tree.push(mappedElem);
}
}
}
return tree;
}
Here is working POC of Recursive Component and tree data in action:
https://stackblitz.com/edit/react-7jhe22?file=index.js
The POC shows automatically adding a random comment to mimic the behavior of user adding a comment.
This also shows how you can append at the end of comments array and still generate comment view with help of unflatten function. Since this is recursive, you can reply to any comment!!

How to highlight continent

I have to show statistics on a continent level (Europe, Asia, etc.).
How can I pass the data? I can find only samples to pass the data on a country level like:
var sample_data0 = { "de": "10000", "at": "15000", "pl": "5000" };
I would like something like:
var sample_continent-data = { "Europe": "10000", "Asia": "15000", "northamerica": "5000" };
I know this is old but here's an answer for you....
Replace the code in your jquery.vmap.world.js file with this file (make a back up of your original):
http://www.filedropper.com/jqueryvmapworld
(There's too much data to paste it here - hence the link to a file.)
This will give you a map with continents rather than countries.
Then replace the code in jquery.vmap.sampledata.js with:
var sample_data = { "AF": "152.23", "NA": "11.58", "OC": "158.97", "AS": "85.81", "EU": "1.1", "SA": "351.02" };
That should just work now (assuming you had the basic maps working) - comment if anything has gone wrong, or the linked file has disappeared.

Resources