MongoDB - How to unwind object of array - javascript

I am trying to manipulate a dataset to make it easy to display in mongoCharts. There are two sets of team_a and team_b, each contains a set of playerId, score, rank, and prize. I want to unwind the array inside the Object and also want to merge both arrays into one.
Sample Document:
{
team_a: {
team_score: 94,
team_name: "team_1",
players: [
{
id: "604f00d43776e45a448628f9",
username: "test_1",
score: "33",
rank: "1",
prize: 15.4,
},
{
id: "60058dd9b88cc1a1e40f2f54",
username: "test_2",
score: "31",
rank: "2",
prize: 15.4,
},
{
id: "60058dd9b88cc1a1e40f2f55",
username: "test_3",
score: "30",
rank: "3",
prize: 15.4,
}
],
},
team_b: {
team_score: 62,
team_name: "team_2",
players: [
{
id: "602ce34a39c7496600940774",
username: "test_4",
score: "32",
rank: "1",
},
{
id: "60058db6b88cc1a1e40f2f4f",
username: "test_5",
score: "30",
rank: "2",
},
],
},
}
And the desired output is:
{
team_a: [
{
username: "test_1",
score: "33",
rank: "1",
prize: 15.4,
},
{
username: "test_2",
score: "31",
rank: "2",
prize: 15.4,
},
{
username: "test_3",
score: "30",
rank: "3",
prize: 15.4,
}
],
team_b: [
{
username: "test_4",
score: "32",
rank: "1",
},
{
username: "test_5",
score: "30",
rank: "2",
},
],
all_winners: [
{
username: "test_1",
score: "33",
rank: "1",
prize: 15.4,
},
{
username: "test_2",
score: "31",
rank: "2",
prize: 15.4,
},
{
username: "test_3",
score: "30",
rank: "3",
prize: 15.4,
}
{
username: "test_4",
score: "31",
rank: "4",
},
{
username: "test_5",
score: "30",
rank: "5",
},
]
}
Any guidance or pointers are gratefully received.
Thanks.

Solution 1
1st $project stage:
team_a field with team_a.players
team_b field with team_b.players
all_winners field with $concatArrays for team_a.players and team_b.players
2nd $project stage:
Remove id field from team_a, team_b, all_winners array fields.
db.collection.aggregate([
{
$project: {
"team_a": "$team_a.players",
"team_b": "$team_b.players",
"all_winners": {
"$concatArrays": [
"$team_a.players",
"$team_b.players"
]
}
}
},
{
$project: {
"all_winners": {
id: 0
},
"team_a": {
id: 0
},
"team_b": {
id: 0
}
}
}
])
Sample Mongo Playground (Solution 1)
Solution 2
Alternative, use $unset to remove team_a.players.id and team_b.players.id as first stage.
db.collection.aggregate([
{
$unset: [
"team_a.players.id",
"team_b.players.id"
]
},
{
$project: {
"team_a": "$team_a.players",
"team_b": "$team_b.players",
"all_winners": {
"$concatArrays": [
"$team_a.players",
"$team_b.players"
]
}
}
}
])
Sample Mongo Playground (Solution 2)

Related

JS - manipulate variables on Object.assign

How can I manipulate variables inside - map.set(key, Object.assign({}, item));.
Array for example -
const arr = [
{
name: "daniel",
sum: "$100",
},
{
name: "daniel",
sum: "100",
},
{
name: "daniel",
sum: "$100",
},
{
name: "daniel",
sum: "100",
},
];
desired output -
const arr = [
{
name: "daniel",
sum: "100",
},
{
name: "daniel",
sum: "100",
},
{
name: "daniel",
sum: "100",
},
{
name: "daniel",
sum: "100",
},
];
How can I split for the example inside the assign?

Find all values of a particular key in a array of objects or object of objets

I have an array of objects as below
let arr = [
{
name: "string 1",
details: [
{
id: 1,
values: [
{ date: "12-Mar", score: "15" },
{ date: "13-Mar", score: "16" },
{ date: "14-Mar", score: "17" },
{ date: "15-Mar", score: "18" },
],
},
],
},
{
name: "string 2",
details: [
{
id: 2,
values: [
{ date: "12-Mar", score: "16" },
{ date: "13-Mar", score: "17" },
{ date: "14-Mar", score: "18" },
{ date: "15-Mar", score: "19" },
],
},
],
},
{
name: "string 3",
details: [
{
id: 2,
values: [
{ date: "12-Mar", score: "21" },
{ date: "13-Mar", score: "22" },
{ date: "14-Mar", score: "23" },
{ date: "15-Mar", score: "24" },
],
},
],
},
];
I also have the same data as an object of objects as below
let obj = {
"string 1": {
details: [
{
id: 1,
values: [
{ date: "12-Mar", score: "15" },
{ date: "13-Mar", score: "16" },
{ date: "14-Mar", score: "17" },
{ date: "15-Mar", score: "18" },
],
},
],
},
"string 2": {
details: [
{
id: 2,
values: [
{ date: "12-Mar", score: "16" },
{ date: "13-Mar", score: "17" },
{ date: "14-Mar", score: "18" },
{ date: "15-Mar", score: "19" },
],
},
],
},
"string 3": {
details: [
{
id: "2",
values: [
{ date: "12-Mar", score: "21" },
{ date: "13-Mar", score: "22" },
{ date: "14-Mar", score: "23" },
{ date: "15-Mar", score: "24" },
],
},
],
},
};
I want to find all the dates & all the scores as an array.
For the array of ojects, with the help of answer here (How to find all values of a specific key in an array of nested objects?), I was able to get the result with the code below.
Since I did not want the dates to be repeated, I created a Set
dates = new Set(getValue(arr, "date"))
However, for the object of objects, I am not able to get the results. How do I go about it.
Also, I have the option to get my data as an array of objects or an object of objects. Since I have to perform a lot of manipulation/analysis (I will be using this with D3 library t build charts), which is the better format? Can anyone guide? Thanks.
You could use a recursive approach (as in the referenced answer) to pick all properties for a given key. One can also add a unique parameter, if this is set to true we'll create a Set from the properties to ensure we don't return any duplicates:
let arr = [ { name: "string 1", details: [ { id: 1, values: [ { date: "12-Mar", score: "15" }, { date: "13-Mar", score: "16" }, { date: "14-Mar", score: "17" }, { date: "15-Mar", score: "18" }, ], }, ], }, { name: "string 2", details: [ { id: 2, values: [ { date: "12-Mar", score: "16" }, { date: "13-Mar", score: "17" }, { date: "14-Mar", score: "18" }, { date: "15-Mar", score: "19" }, ], }, ], }, { name: "string 3", details: [ { id: 2, values: [ { date: "12-Mar", score: "21" }, { date: "13-Mar", score: "22" }, { date: "14-Mar", score: "23" }, { date: "15-Mar", score: "24" }, ], }, ], }, ];
let obj = { "string 1": { details: [ { id: 1, values: [ { date: "12-Mar", score: "15" }, { date: "13-Mar", score: "16" }, { date: "14-Mar", score: "17" }, { date: "15-Mar", score: "18" }, ], }, ], }, "string 2": { details: [ { id: 2, values: [ { date: "12-Mar", score: "16" }, { date: "13-Mar", score: "17" }, { date: "14-Mar", score: "18" }, { date: "15-Mar", score: "19" }, ], }, ], }, "string 3": { details: [ { id: "2", values: [ { date: "12-Mar", score: "21" }, { date: "13-Mar", score: "22" }, { date: "14-Mar", score: "23" }, { date: "15-Mar", score: "24" }, ], }, ], }, };
function getProperties(obj, key, unique = true, result = []) {
for(let k in obj) {
if (typeof(obj[k]) === 'object') {
getProperties(obj[k], key, unique, result);
} else if (k === key) {
result.push(obj[k]);
}
}
return unique ? [...new Set(result)]: result;
}
console.log('Dates (arr):', JSON.stringify(getProperties(arr, 'date', true)))
console.log('Scores (arr):', JSON.stringify(getProperties(arr, 'score', true)))
console.log('Dates (obj):', JSON.stringify(getProperties(obj, 'date', true)))
console.log('Scores (obj):', JSON.stringify(getProperties(obj, 'score', true)))
You can iterate over the top-level keys in your object like this:
for (let key in obj){
let val = obj[key]
/* From here you can proceed with finding all values
like you did with the array
*/
}

Update object value in array with values in other array using hashtables or hashmap

I have two arrays Array1 and Array2, i am updating rate of object in Array1 with rate of same object (With same ID) in Array 2. I have a functions that loops through both arrays to get desired result. After going through some of the answers on Stack overflow I feel Hash table is best suited to reduce the complexity. I was just curious to understand how same can be implemented using the has maps.
let Array1 = [{
id: 1,
name: "IceCream",
details: [{
id: "12",
name: "milk",
quantity: "50",
rate: "100"
},
{
id: "13",
name: "cream",
quantity: "50",
rate: "300"
}
]
},
{
id: 2,
name: "Coffee",
details: [{
id: "14",
name: "Coffee bean",
quantity: "60",
rate: "200"
},
{
id: "15",
name: "water",
quantity: "60",
rate: "300"
}
]
},
{
id: 3,
name: "Tea",
details: [{
id: "16",
name: "Tea leaf",
quantity: "50",
rate: "700"
}]
}
]
let Array2 = [{
id: 1,
name: "IceCream",
details: [{
id: "12",
name: "milk",
quantity: "50",
rate: "500"
},
{
id: "13",
name: "cream",
quantity: "50",
rate: "700"
}
]
},
{
id: 2,
name: "Coffee",
details: [{
id: "14",
name: "Coffee bean",
quantity: "60",
rate: "800"
},
{
id: "15",
name: "water",
quantity: "60",
rate: "8000"
}
]
}
]
Array1 = Array1.map(item => {
let element = Array2.find(e => e.id == item.id);
if (element) {
item.details = item.details.map(e => {
let detail = element.details.find(d => d.id == e.id);
if (detail)
e.rate = detail.rate;
return e;
});
}
return item;
});
console.log(Array1);
Make a map of Array2's items (by id) and each of Array2's details (by id), and then you can iterate over Array1 and mutate its properties with low complexity:
const items2ById = {};
for (const item of Array2) {
items2ById[item.id] = item;
}
const items2DetailsById = {};
for (const detail of Array2.flatMap(({ details }) => details)) {
items2DetailsById[detail.id] = detail;
}
for (const item of Array1) {
if (!items2ById[item.id]) continue;
for (const detail of item.details) {
if (items2DetailsById[detail.id]) {
detail.rate = items2DetailsById[detail.id].rate;
}
}
}
Note that since you're mutating the existing objects, .map isn't really appropriate, since you don't really care to create a new array - instead, just iterate over the array and mutate it as needed.
let Array1 = [{
id: 1,
name: "IceCream",
details: [{
id: "12",
name: "milk",
quantity: "50",
rate: "100"
},
{
id: "13",
name: "cream",
quantity: "50",
rate: "300"
}
]
},
{
id: 2,
name: "Coffee",
details: [{
id: "14",
name: "Coffee bean",
quantity: "60",
rate: "200"
},
{
id: "15",
name: "water",
quantity: "60",
rate: "300"
}
]
},
{
id: 3,
name: "Tea",
details: [{
id: "16",
name: "Tea leaf",
quantity: "50",
rate: "700"
}]
}
]
let Array2 = [{
id: 1,
name: "IceCream",
details: [{
id: "12",
name: "milk",
quantity: "50",
rate: "500"
},
{
id: "13",
name: "cream",
quantity: "50",
rate: "700"
}
]
},
{
id: 2,
name: "Coffee",
details: [{
id: "14",
name: "Coffee bean",
quantity: "60",
rate: "800"
},
{
id: "15",
name: "water",
quantity: "60",
rate: "8000"
}
]
}
];
const items2ById = {};
for (const item of Array2) {
items2ById[item.id] = item;
}
const items2DetailsById = {};
for (const detail of Array2.flatMap(({ details }) => details)) {
items2DetailsById[detail.id] = detail;
}
for (const item of Array1) {
if (!items2ById[item.id]) continue;
for (const detail of item.details) {
if (items2DetailsById[detail.id]) {
detail.rate = items2DetailsById[detail.id].rate;
}
}
}
console.log(Array1);

Accessing an object property from outside scope

So I have 4 jsons with that looks like this:
{
"group": "A",
"id": "50"
"person": [
{
"name": 'Joe',
"age": '29'
},
{
"name": 'Jessie',
"age": '27'
}
]
}
I used this function to create an array with all the people from 4 different json's files.
list.forEach(list => {
list.person.forEach(person => {
peopleArray.push(person);
});
})
The problem is, when I pick a position from that array, I want to be able to access the group and the ID as well for example:
console.log(peopleArray[1].group);
Is that possible? Or I would have to those values inside the person?
Just include those values in the person object
const data = {
group: "A",
id: "50",
person: [
{
name: 'Joe',
age: '29'
},
{
name: 'Jessie',
age: '27'
}
]
}
data.person.map(obj => ({...obj, group: data.group, groupId: data.id}))
The result is:
[
{
age: "29",
group: "A",
groupId: "50",
name: "Joe"
},
{
age: "27",
group: "A",
groupId: "50",
name: "Jessie"
}
]

How to get unique Id for multiple duplicate properties

say we have a object:
var db = [
{Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" },
{Id: "202", Player: "Sam",price: "4.22", loc: "PA" },
{Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" },
{Id: "204", Player: "Bill",price: "3.22", loc: "TX" },
{Id: "205" ,Player: "Dave",price: "3.99", loc: "WA" },
{Id: "206" ,Player: "Dave",price: "3.99", loc: "WI" },
];
202&203 and 205&206 have similar values for player and price but I need just one id for similar values i.e, output should be 202,205.
Can someone help me with that.
You could filter it with a hash table for look up for the same player and price values.
var db = [{ Id: "201", Player: "Jon", price: "3.99", loc: "NJ" }, { Id: "202", Player: "Sam", price: "4.22", loc: "PA" }, { Id: "203", Player: "Sam", price: "4.22", loc: "NY" }, { Id: "204", Player: "Bill", price: "3.22", loc: "TX" }, { Id: "205", Player: "Dave", price: "3.99", loc: "WA" }, { Id: "206", Player: "Dave", price: "3.99", loc: "WI" }],
filtered = db.filter(function (a) {
var key = a.Player + '|' + a.price;
if (!this[key]) {
this[key] = true;
return true;
}
}, Object.create(null))
console.log(filtered);
I think this could be a summarized answer:
var db = [{ Id: "201", Player: "Jon", price: "3.99", loc: "NJ" }, { Id: "202", Player: "Sam", price: "4.22", loc: "PA" }, { Id: "203", Player: "Sam", price: "4.22", loc: "NY" }, { Id: "204", Player: "Bill", price: "3.22", loc: "TX" }, { Id: "205", Player: "Dave", price: "3.99", loc: "WA" }, { Id: "206", Player: "Dave", price: "3.99", loc: "WI" }];
var result = db.filter((v, k) =>
(k = v.Player + v.price) in this ? false :(this[k] = true));
console.log(result);

Categories

Resources