Possible to group multiple entries and form new object for the values? - mongodb-query

I have Orders and Products being connected by a third collection with OrderID, ProductID, Quantity.
I want to get the result grouped something like this:
{
OrderID: 1,
products:[
name: productname1, quantity: 3
name: productname2, quantity: 1
]
},
{
OrderID: 2,
products:[
name: productname3, quantity: 10
name: productname5, quantity: 4
]
}
I have managed to $lookup and $project it down to displaying each coupling/reference on its own:
{
OrderID: 1,
name: productname1,
quantity: 3
},
{
OrderID: 1,
name: productname2,
quantity: 1
},
{
OrderID: 2
...
},
{
OrderID: 2
...
}
Is this to any use, or am i thinking wrong here? I basically tried $push into an object, but that doesn't really work.

Solved it after some head scratching.
Rearranged the last $project for this result instead:
{
OrderID: 1,
product: [{
name: productname1,
quantity: 3
}]
}
I could then run this $group and get my desired result (pushing each entire object from array):
{
_id: "$OrderID",
products: {$push: "$product"}
}

Related

How do I search in redis json

I'm currently new to ioredis and I was wondering how o I can search all the json object that has a key value of something.
Example
rooms:{
roomId1: {
name: "room1",
users: [{userId: 1, name: "bob"}, {userId: 2, name: "joe}]
},
roomId2: {
name: "room2",
users: [{userId: 1, name: "jill"}, {userId: 2, name: "joe}]
},
roomId3: {
name: "room3",
users: [{userId: 6, name: "hoi"}, {userId: 1, name: "bob}]
}
}
and I want find all the rooms that has the user "bob" so I want the output to be
[roomId1: {
name: "room1",
users: [{userId: 1, name: "bob"}, {userId: 2, name: "joe}]
}, roomId3: {
name: "room3",
users: [{userId: 6, name: "hoi"}, {userId: 1, name: "bob}]
}]
How cna i achievee this? I guess I can do something like this
const redis = new Redis();
const roomStates = await redis.get("rooms");
//for loop and inner for loop to find the users name bob
but I was wondeirng if theres a faster way of doing it using the redis built in functions

How to compare two arrays in Standard SQL (BigQuery)?

I have two tables with the exact same schema, one of the fields is a record and I try to compare this field between the two tables.
For example:
Table A:
{ Name: 'Mary',
DOB: '06.06.1970',
Children:[
{ Name: John, Age: 6 },
{ Name: Agatha, Age: 10}
]
},
{ Name: 'Bob',
DOB: '30.03.1982',
Children:[
{ Name: Anthony, Age: 9 },
{ Name: William, Age: 4 },
{ Name: Rose, Age: 2 }
]
},
{ Name: 'Adam',
DOB: '312.10.1980',
Children:[
{ Name: Andrew, Age: 9 },
{ Name: Kate, Age: 4 }
]
}
Table B:
{ Name: 'Mary',
DOB: '06.06.1970',
Children:[
{ Name: John, Age: 6 },
{ Name: Agatha, Age: 10}
]
},
{ Name: 'Bob',
DOB: '30.03.1982',
Children:[
{ Name: Anthony, Age: 9 },
{ Name: George, Age: 4 },
{ Name: Frank, Age: 2 }
]
},
{ Name: 'Adam',
DOB: '312.10.1980',
Children:[
{ Name: Andrew, Age: 9 },
{ Name: Kate, Age: 4 },
{ Name: Jonathan, Age: 2 }
]
}
The output I'd like to get is:
Name
----------
Bob
Adam
Since the Children details are not the same for Bob or Adam in table A and table B (whenever it's the size of the record (num of children) or the details (children names etc...))
I tried to use SELECT UNION DISTINCT but it doesn't work on an array, I also tried != and <> but it doesn't work on arrays...
It would be ideal to compare two arrays like you can compare two lists in Python (comparing the structure and the content).
Is there a way to implement something similar ?
Thank you
select name
from `project.dataset.tableA` a
join `project.dataset.tableB` b
using(name)
where a.dob != b.dob
or (select string_agg(format('%t', s) order by name) from a.children s)
!= (select string_agg(format('%t', s) order by name) from b.children s)

How do I perform a SQL update on a list inside one of my table rows?

I have a table with parameters as shown below.
{
id: 1,
title: 'waccos',
description: 'Making an operating system in wacc',
est_duration: 420,
exp_req: 'any',
langs: [ 1 ],
owner: 1,
members: [ 1, 2 ]
},
I want to use SQL to add a new member into the member list, but I do not know how to. The table is called testprojects. I've tried using
(update testprojects
set members = members || $1
where title is $2;', [name, title])
but I think that is wrong. Could anyone help me please?
This is the table of members so far.
[
{ id: 1, name: 'A' },
{ id: 2, name: 'K' },
{ id: 3, name: 'S' },
{ id: 5, name: 'd' },
{ id: 6, name: 'J' },
{ id: 7, name: 'E' },
{ id: 8, name: 'a' }
]

How to do groupBy and add the sum of the values grouped in underscore.js

From this:
var x = [
{category: 'Title', price: 100 },
{category: 'Title', price: 200 },
{category: 'Title3', price: 300 },
{category: 'Title3', price: 400 },
{category: 'Title5', price: 500 },
];
To this:
var x = [
{category: 'Title', price: 300},
{category: 'Title3', price: 700},
{category: 'Title5', price: 500},
];
The logic is same as SQL query:
SELECT category, sum (price) FROM x GROUP BY category;
Updated:
groupBy will group the initial array by "category".
map will then iterate each object in the grouped array by passing in two params: key and value. The first key will be "Title" and its value is an array of [{category: 'Title', price: 100 }, {category: 'Title', price: 200 }].
Before returning an updated array in map, reduce is used to sum up the "price". Basically, it iterates through the array (first param) and return the sum from the function (second param). Note that in the first iteration, the total will be 0 (last param in reduce). So, the first return will be 0 + 100 which is then passed in as 'new' total in the second iteration and so on.
You can refer to the documentation for more details.
Try this:
var groups = _.groupBy(x, 'category');
var result = _.map(groups, function(value, key) {
return {
category: key,
price: _.reduce(value, function(total, o) {
return total + o.price;
}, 0)
};
});

Creating sorted tree in DOJO 1.6?

I new to learn dojo and trying to learn by it using samples code.
Using dojo 1.6
With help of sample codes , I created a tree
now i want to apply sorting on root and also on child.
With the help of this sample code , i changed the code
Output is not sorted n but the root folder has changed their position and child is deleted.
Plz help me to resolve this.
My code :
dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.tree.ForestStoreModel");
dojo.require("dijit.Tree");
var data = [ { id: 1, name: "answerTypeLabel", type:'scenario', children:[{_reference: 2}]},
{ id: 2, name: "acceptRequestLabel", type:'paragraph', data: "acceptRequestLabel"},
{ id: 3, name: "rejectRequestLabel", type:'scenario', children:[{_reference: 5},{_reference: 6}]},
{ id: 4, name: "MoreInformationLabel", type:'scenario', children:[{_reference: 7},{_reference: 8}]},
{ id: 5, name: "rejectRequestStatusLabel", type:'paragraph', data: "rejectRequestStatusLabel"},
{ id: 6, name: "rejectRequestNotCoveredLabel", type:'paragraph', data: "rejectRequestNotCoveredLabel" },
{ id: 7, name: "MoreInformationDocumentLabel", type:'paragraph', data: "MoreInformationDocumentLabel"},
{ id: 8, name: "MoreInformationDataLabel", type:'paragraph', data: "MoreInformationDataLabel"}
];
dojo.addOnLoad(function() {
var sortableStore = new dojo.data.ItemFileReadStore({
data: {
identifier: 'id',
label: 'name',
items: data
}
});
var model = new dijit.tree.ForestStoreModel({
rootLabel: 'Names',
store: new dojo.data.ItemFileWriteStore({
data: {
identifier: 'id',
items: [],
label: 'name'
}
}) // blank itemsstore
})
var tree = new dijit.Tree({
model: model,
updateItems: function(items) {
var self = this;
console.log('pre', this.model.root.children);
dojo.forEach(items, function(newItem) {
console.log('add', newItem);
try {
self.model.store.newItem({
id: sortableStore.getValue(newItem, 'id'),
name: sortableStore.getValue(newItem, 'name'),
type: sortableStore.getValue(newItem, 'type'),
data: sortableStore.getValue(newItem, 'data'),
});
} catch (e) {
console.log(e);
}
});
console.log('post', this.model.root.children);
console.log("children: ", this.rootNode.getChildren());
},
});
tree.placeAt(dojo.body());
sortableStore.fetch({
query: {
type:'scenario'
},
sort: [{
attribute: "name"}],
onComplete: function(items) {
console.log(items, 'sorted');
tree.updateItems(items);
}
})
});
Output :
The 'Names' origins from you setting 'rootLabel'.
Btw, fiddles have revisions and is simply a paste-bin like feature :)
You need to use the tree model pasteItem to insert referenced items (the 'children' property of each 'newItem').
Otherwise, there's another approach, if you get rid of the '_reference' structure of your data. See: http://jsfiddle.net/GHFdA/1/