How can I get only the data from menus which _id is 1?
I've tried:
db.collection("restaurants")
.find({ name : String(name), "menus._id": Number(id)} )
.toArray(function (err, result) {
But I still get the full result from restaurant and not only the menu
you have to use projection to retrieve only the menus field.
db.collection("restaurants").find( { name: String(name), "menus._id": Number(id) }, { _id: 0, menus: 1 } ).toArray( function(err,result) { } );
with or without projection the _id field is returned by default, you have to turn it off by setting the _id field to 0. 0 means don't show the value of this field, while 1 does the opposite
Related
My http request will return below data:
It returns below data:
Users.js
{
{
...
friends:[]
},
{
...
friends:[{id:xxx,...},...]
},
{
...
friends:[]
},
}
If I want to use query to get all data whose friends array is [],
should I do below query.
select * from users where (what should I write here)
If friends is a direct column in your database is JSON array. You can use JSON_LENGTH to find out the length of array.
SELECT JSON_LENGTH('[1, 2, {"a": 3}]'); // Output: 3
SELECT JSON_LENGTH('[]'); // Output: 0
You can use same concept to get data from your database.
select *
FROM users
WHERE JSON_LENGTH(friends) = 0;
If you've nested JSON and one of key is friends in that json for given column(data) then your query would be like using JSON_CONTAINS
SELECT *
FROM users
WHERE JSON_CONTAINS(data, JSON_ARRAY(), '$.friends') -- To check do we have `friends` as key in that json
and JSON_LENGTH(data, '$.friends') = 0; -- To check whether it is empty array.
Now you can convert it to sequelize query. One of the way you can use is
Model.findAll({
where: {
[Op.and]: [
Sequelize.literal('RAW SQL STATEMENT WHICH WONT BE ESCAPED!!!')
]
}
})
Make sure to update Model with your user model and query.
I have the following json :
[
{
"transition":"random_word",
"from":"paris",
"to":"porto",
"date":{
"date":"2020-05-28 11:51:25.201864",
"timezone_type":3,
"timezone":"Europe\/Paris"
}
},
{
"transition":"rainbow",
"from":"porto",
"to":"faro",
"date":{
"date":"2020-06-06 23:10:06.878539",
"timezone_type":3,
"timezone":"Europe\/Paris"
}
},
{
"transition":"banana",
"from":"faro",
"to":"rio_de_janeiro",
"date":{
"date":"2020-06-06 23:14:10.975099",
"timezone_type":3,
"timezone":"Europe\/Paris"
}
},
{
"transition":"hello",
"from":"rio_de_janeiro",
"to":"buenos_aires",
"date":{
"date":"2020-06-06 23:14:15.314370",
"timezone_type":3,
"timezone":"Europe\/Paris"
}
}
]
Imagine I want to retrieve the last stop of my traveler (the value of the key "to" from the last json object. Here : buenos_aires) and the date (here :2020-06-06 23:14:15.314370).
How should I proceed knowing that I want to do that using PostgreSQL?
If with "last" you mean the order in which the elements show up in the array, you can use jsonb_array_length() to get the length of the array and use that to obtain the last element:
select (the_json_column -> jsonb_array_length(the_json_column) - 1) ->> 'to' as "to",
(the_json_column -> jsonb_array_length(the_json_column) - 1) #>> '{date,date}' as "date"
from the_table
The expression jsonb_array_length(the_json_column) - 1 calculates the index of the "last" element in the array.
If your column is defined as json rather than jsonb (which it should be) you need to use the equivalent json_array_length() instead.
I have a collection in which I want to add a new field and in that field i want to randomly assign values between 1 and 44 in mongo db.
I have already tried math.random() which is not working.
{ $addFields:{ PoS_ID: { $switch:{ branches:[ { case: {$and : [{$gte: ["$user_id", 0]}, {$lte: ["$user_id", 10000]}]}, then:1 }, { case: {$and : [{$gte: ["$user_id", 10000]}, {$lte: ["$user_id", 15000]}]}, then:2 } ], default: -1 } } } }
This lets me assign pos_ids from 1 to 44 to different user ids based on conditions.But I want to simply assign each and every user id with a random number between 1 to 44.
I'm experiencing an issue with apollo client caching, and I'm not sure I understand why. I'm building an angular 6 app, using apollo-boost, all is working well. I have a scenario now where my a graphql query takes an id (of a user) and a filter string (used to filter records on the backend). The angular component code looks like:
ngOnInit() {
this.filter$.subscribe(filterValue => {
this.route.params.subscribe(this.getAppointments.bind(this, filterValue));
});
}
The getAppointments function looks like:
getAppointments(filter: string, params: {id: string}) {
this.artistAppointmentBookGQL.watch({artistId: user.artist._id, filter}).valueChanges
.pipe(
map(results => {
// THIS ALWAYS RUNS WHEN THE FILTER CHANGES
// HOWEVER THE RESULTS ARE ALWAYS THE LAST QUERY RUN
// IF THE FILTER HAS BEEN RUN BEFORE
console.log(user.artist._id, filter, results.data.artist.appointmentBook);
return results.data.artist.appointmentBook;
}));
}
The graphql query:
query artistAppointmentBook($artistId: ID!, $filter: String) {
artist(id: $artistId, appointmentType: $filter) {
_id
appointmentBook {
_id
created_at
firstName
lastName
date
price
stripe {
charge {
id
amount
}
}
}
}
The main issue:
I have 4 different possible filter values (all, unconfirmed, confirmed, paid). When I run these queries with each filter value, it works as expected, and I get back the proper result sets from the apollo server. However, as soon as I run the same query twice, I only get back the result of whatever the last query was, and no network call is made, presumably because it's using a cached version.
Shouldn't the cache be based on the variable inputs? It seems to run fine the first time I run with different variables, but as soon as one gets duplicated I only get back whatever the last call yielded. Thanks for any help!
This gif demonstrates the issue:
Figured out my issue. As it should, apollo is caching the artist record because it has an _id and a type. The filter was being passed into artist query, when it should have been passed in at the appointmentBook level. I updated my schema to accept the filter param and then passed it in there instead of into the artist query.
Originally I had:
query artistAppointmentBook($artistId: ID!, $filter: String) {
artist(id: $artistId, appointmentType: $filter) {
_id
appointmentBook {
_id
created_at
firstName
lastName
date
price
stripe {
charge {
id
amount
}
}
}
}
Which needed to be changed to:
query artistAppointmentBook($artistId: ID!, $filter: String) {
artist(id: $artistId) {
_id
appointmentBook(filter: $filter) {
_id
created_at
firstName
lastName
date
price
stripe {
charge {
id
amount
}
}
}
}
After this update, the queries are cached properly.
I've had a hard time getting two columns from a CSV file with which I am planning on building a basic bar chart. I was planning on getting 2 arrays (one for each column) within one array that I would use as such to build a bar chart. Just getting started with D3, as you can tell.
Currently loading the data in gets me an array of objects, which is then a mess to get two columns of key-value pairs. I'm not sure my thinking is correct...
I see this similar question:
d3 - load two specific columns from csv file
But how would I use selections and enter() to accomplish my goal?
You can't load just 2 columns of a bigger CSV, but you can load the whole thing and extract the columns you want.
Say your csv is like this:
col1,col2,col3,col4
aaa1,aaa2,aaa3,aaa4
bbb1,bbb2,bbb3,bbb4
ccc1,ccc2,ccc3,ccc4
And you load it with
csv('my.csv', function(err, data) {
console.log(data)
/*
output:
[
{ col1:'aaa1', col2:'aaa2', col3:'aaa3', col4:'aaa4' },
{ col1:'bbb1', col2:'bbb2', col3:'bbb3', col4:'bbb4' },
{ col1:'ccc1', col2:'ccc2', col3:'ccc3', col4:'ccc4' }
]
*/
})
If you only want col2 and col3 (and you don't want to simply leave the other columns' data in there, which shouldn't be an issue anyway), you can do this:
var cols2and3 = data.map(function(d) {
return {
col2: d.col2,
col3: d.col3
}
});
console.log(cols2and3)
/*
output:
[
{ col2:'aaa2', col3:'aaa3' },
{ col2:'bbb2', col3:'bbb3' },
{ col2:'ccc2', col3:'ccc3' }
]
*/
I.e. the above code produced a new array of objects with only two props per object.
If you want just an array of values per column — not objects with both columns' values — you can:
var col2data = data.map(function(d) { return d.col2 }
var col3data = data.map(function(d) { return d.col3 }
console.log(col2) // outputs: ['aaa2', 'bbb2', 'ccc2']