I have the following documents in MongoDB:
{
name: "document1",
data: [{
name: "xxxxx",
status: "delivered"
},{
name: "xxxxx",
status: "In Process"
},{
name: "xxxxx",
status: "Not Started"
}]
},{
name: "document2",
data: [{
name: "xxxxx",
status: "delivered"
},{
name: "xxxxx",
status: "delivered"
},{
name: "xxxxx",
status: "delivered"
}]
}
I want to find all documents where all objects inside the "data" array have the status "delivered", I used to use $ne: 'Not Started', but now that more status options have been introduced, this doesn't work. Perhaps I could do a $ne: $and and include all negative options, but any new status will give issues.
You can use $not with $elemMatch
db.collection.find({
"data": {
"$not": {
"$elemMatch": {
"status": {
$ne: "delivered"
}
}
}
},
"data.status": "delivered"
})
Here is fiddle https://mongoplayground.net/p/digdoFC6yF0
You can use $not.
{
$and: [
{ 'data.status': { $not: /Not Started/},
{'data.status': "delivered"}
]
}
Note that $not must receive a regex and not just plain string.
Related
Now, I'm building a social media website using React + Amplify.
And article feature is one of the main feature of it.
But now, I'm facing a difficult issue for me.
I'm trying to get such kind of JSON object from my API.
{
"Article": {
"id": "some ID",
"title": "some String",
"content": "some Content",
"comments": [
"0": {
"comment": {
"id": "some ID",
"content": "some Content",
"owner": {
"id": "some ID",
"name": "name",
"avatar": "avatar"
},
"replys": [
"0": {
"reply": {
"id": "some ID",
"content": "some Content",
"owner": {
"id": "some ID",
"name": "name",
"avatar": "avatar"
}
}
]
}
}
}
]
}
}
For this, I've created schemas on my backend (Amplify API) like this.
type Article
#model
#key( name: "articleByOwner" fields: ["ownerID", "createdAt"] queryField: "articleByOwner")
#key( name: "articleByStatus" fields: ["status", "createdAt"] queryField: "articleByStatus") {
id: ID!
title: String!
content: String!
comments: [Comment] #connection(keyName: "commentByArticle", fields: ["id"])
createdAt: AWSDateTime!
}
type Comment
#model
#key(name: "commentByArticle" fields: ["articleID", "createdAt"] queryField: "commentByArticle")
{
id: ID!
content: String!
ownerID: ID!
owner: Userinfo #connection(fields: ["ownerID"])
articleID: ID!
replys: [Reply] #connection(keyName: "replyByComment", fields: ["id"])
createdAt: AWSDateTime!
}
type Reply
#model
#key(name: "replyByComment" fields: ["commentID", "createdAt"] queryField: "replyByComment" )
{
id: ID!
content: String!
ownerID: ID!
owner: Userinfo #connection(fields: ["ownerID"])
commentID: ID!
createdAt: AWSDateTime!
}
type Userinfo #model {
id: ID!
name: String
avatar: String
createdAt: AWSDateTime!
}
But now, I can get only until comments.
I want this to be done until owner and replyes.
current state is like this. after executing getArticle query.
This query is generated when I push my project to the cloud using "amplify push" command.
{
"Article": {
"id": "some ID",
"title": "some String",
"content": "some Content",
"comments": [
"0": {
"comment": {
"id": "some ID",
"content": "some Content",
"owner": { nextToken: null },
"replys": { nextToken : null }
}
}
]
}
}
Is there any solution for this?
I have a json object for chart like below:
{
"results": [
{
"dataSets": {
"One": {
"label": "testLabel",
"labels": "test",
"data": [
"10",
"58"
]
}
},
"chart": [
{
"key": "test",
"label": "chart-1",
"chartType": "bar",
"order": "1",
"dataSets": [
{
"style": "line",
"key": "One"
},
]
}
]
}
]
}
I want to get dataSets values like label, labels, data of “one” in chart’s dataSets by providing “one” as key.
Is it possible to do in javascript or vue?
Yes, it is possible. But you will need to make a series of Array.map() to achieve this.
const results = [{
dataSets: {
One: {
label: "testLabel",
labels: "test",
data: ["10", "58"]
}
},
chart: [{
key: "test",
label: "chart-1",
chartType: "bar",
order: "1",
dataSets: [{
style: "line",
key: "One"
}]
}]
}];
const modifiedResult = results.map(result => {
const outerDataSets = result.dataSets;
result.chart = result.chart.map(chart =>
chart.dataSets.map(innerDataSet => ({
...innerDataSet,
...outerDataSets[innerDataSet.key]
}))
);
return result;
});
console.log(modifiedResult);
Also if you are working with Vue, I think its best to put the modification of result on the computed so it will always try to add those dataSets additional data to the chart's dataSets.
Here a sample demo for implementation in Vue.
The examples here don't go nearly far enough in explaining how to produce a more complicated structure...
If I want to end up with something like:
{
"data": {
"type": "mobile_screens",
"id": "1",
"attributes": {
"title": "Watch"
},
"relationships": {
"mobile_screen_components": {
"data": [
{
"id": "1_1",
"type": "mobile_screen_components"
},
{
"id": "1_2",
"type": "mobile_screen_components"
},
...
]
}
}
},
"included": [
{
"id": "1_1",
"type": "mobile_screen_components",
"attributes": {
"title": "Featured Playlist",
"display_type": "shelf"
},
"relationships": {
"playlist": {
"data": {
"id": "938973798001",
"type": "playlists"
}
}
}
},
{
"id": "938973798001",
"type": "playlists",
"relationships": {
"videos": {
"data": [
{
"id": "5536725488001",
"type": "videos"
},
{
"id": "5535943875001",
"type": "videos"
}
]
}
}
},
{
"id": "5536725488001",
"type": "videos",
"attributes": {
"duration": 78321,
"live_stream": false,
"thumbnail": {
"width": 1280,
"url":
"http://xxx.jpg?pubId=694940094001",
"height": 720
},
"last_published_date": "2017-08-09T18:26:04.899Z",
"streams": [
{
"url":
"http://xxx.m3u8",
"mime_type": "MP4"
}
],
"last_modified_date": "2017-08-09T18:26:27.621Z",
"description": "xxx",
"fn__media_tags": [
"weather",
"personality"
],
"created_date": "2017-08-09T18:23:16.830Z",
"title": "NOAA predicts most active hurricane season since 2010",
"fn__tve_authentication_required": false
}
},
...,
]
}
what is the most simple data structure and serializer I can set up?
I get stumped after something like:
const mobile_screen_components = responses.map((currentValue, index) => {
id[`id_${index}`];
});
const dataSet = {
id: 1,
title: 'Watch',
mobile_screen_components,
};
const ScreenSerializer = new JSONAPISerializer('mobile_screens', {
attributes: ['title', 'mobile_screen_components'],
mobile_screen_components: {
ref: 'id',
}
});
Which only gives me:
{
"data": {
"type": "mobile_screens",
"id": "1",
"attributes": { "title": "Watch" },
"relationships": {
"mobile-screen-components": {
"data": [
{ "type": "mobile_screen_components", "id": "1_0" },
{ "type": "mobile_screen_components", "id": "1_1" },
{ "type": "mobile_screen_components", "id": "1_2" },
{ "type": "mobile_screen_components", "id": "1_3" },
{ "type": "mobile_screen_components", "id": "1_4" },
{ "type": "mobile_screen_components", "id": "1_5" }
]
}
}
}
}
I have no idea how to get the "included" sibling to "data." etc.
So, the question is:
what is the most simple data structure and serializer I can set up?
Below is the simplest object that can be converted to JSON similar to JSON in the question using jsonapi-serializer:
let dataSet = {
id: '1',
title: 'Watch',
mobile_screen_components: [
{
id: '1_1',
title: 'Featured Playlists',
display_type: 'shelf',
playlists: {
id: 938973798001,
videos: [
{
id: 5536725488001,
duration: 78321,
live_stream: false
},
{
id: 5535943875001,
duration: 52621,
live_stream: true
}
]
}
}
]
};
To serialize this object to JSON API, I used the following code:
let json = new JSONAPISerializer('mobile_screen', {
attributes: ['id', 'title', 'mobile_screen_components'],
mobile_screen_components: {
ref: 'id',
attributes: ['id', 'title', 'display_type', 'playlists'],
playlists: {
ref: 'id',
attributes: ['id', 'videos'],
videos: {
ref: 'id',
attributes: ['id', 'duration', 'live_stream']
}
}
}
}).serialize(dataSet);
console.log(JSON.stringify(json, null, 2));
The first parameter of JSONAPISerializer constructor is the resource type.
The second parameter is the serialization options.
Each level of the options equals to the level of the nested object in serialized object.
ref - if present, it's considered as a relationships.
attributes - an array of attributes to show.
Introduction
First of all we have to understand the JSON API document data structure
[0.1] Refering to the top level (object root keys) :
A document MUST contain at least one of the following top-level
members:
data: the document’s “primary data”
errors: an array of error objects
meta: a meta object that contains non-standard meta-information.
A document MAY contain any of these top-level members:
jsonapi: an object describing the server’s implementation
links: a links object related to the primary data.
included: an array of resource objects that are related to the primary data and/or each other (“included resources”).
[0.2]
The document’s “primary data” is a representation of the resource or
collection of resources targeted by a request.
Primary data MUST be either:
a single resource identifier object, or
null, for requests that target single resources
an array of resource identifier
objects, or an empty array ([]), for reqs. that target
collections
Example
The following primary data is a single resource object:
{
"data": {
"type": "articles",
"id": "1",
"attributes": {
// ... this article's attributes
},
"relationships": {
// ... this article's relationships
}
}
}
In the (jsonapi-serializer) documentation : Available serialization option (opts argument)
So in order to add the included (top-level member) I performed the following test :
var JsonApiSerializer = require('jsonapi-serializer').Serializer;
const DATASET = {
id:23,title:'Lifestyle',slug:'lifestyle',
subcategories: [
{description:'Practices for becoming 31337.',id:1337,title:'Elite'},
{description:'Practices for health.',id:69,title:'Vitality'}
]
}
const TEMPLATE = {
topLevelLinks:{self:'http://example.com'},
dataLinks:{self:function(collection){return 'http://example.com/'+collection.id}},
attributes:['title','slug','subcategories'],
subcategories:{ref:'id',attributes:['id','title','description']}
}
let SERIALIZER = new JsonApiSerializer('pratices', DATASET, TEMPLATE)
console.log(SERIALIZER)
With the following output :
{ links: { self: 'http://example.com' },
included:
[ { type: 'subcategories', id: '1337', attributes: [Object] },
{ type: 'subcategories', id: '69', attributes: [Object] } ],
data:
{ type: 'pratices',
id: '23',
links: { self: 'http://example.com/23' },
attributes: { title: 'Lifestyle', slug: 'lifestyle' },
relationships: { subcategories: [Object] } } }
As you may observe, the included is correctly populated.
NOTE : If you need more help with your dataSet, edit your question with the original data.
Help anyone, I need to use JSON data in my store. Can someone point what is wrong in my jsonstore config? I need to use the rain_value and air_pressure parameter in my graph but 'data' in JSON wont be set as root.
My device model:
Ext.define('device', {
extend: 'Ext.data.Model',
config: {
fields : [
{
name : 'dev_id',
type : 'int'
},
{
name : 'location'
}
],
hasMany : [
{
model : 'stationData',
name : 'data',
associationKey : 'data'
},
]
}
});
My deviceData model:
Ext.define('stationData', {
extend : 'Ext.data.Model',
config : {
fields : [
'dateTimeRead',
'rain_value',
'air_pressure'
]
}});
My jsonStore:
var store = new Ext.data.Store({
autoLoad : true,
model : 'device',
proxy : {
type : 'ajax',
url : 'dataURL',
reader: {
type: 'json',
root: 'data'
},
}
});
JSON Data:
[{
"dev_id": 171,
"location": "Sample location",
"province": "Sample Province",
"cell_num": "0123456789",
"posx": "longitude",
"posy": "latitude",
"elevation": "105",
"battery": "LP",
"region": "VI",
"type_id": "AWS",
"imei_num": "300234011463010",
"is_ftp": false,
"data": [{
"dateTimeRead": "2013-11-14 11:45:32",
"rain_value": "0.52",
"rain_intensity": "19.3",
"air_pressure": "1002.02",
"wind_speed": "7.9",
"air_humidity": "76.7",
"solar_radiation": "-305363.70",
"wind_direction": "327",
"air_temperature": "29.2",
"rain_cum": "238.07",
"soil_moisture1": "8.88",
"soil_temperature1": "28.7",
"soil_moisture2": "6.37",
"soil_temperature2": "27.6",
"rain_duration": "180",
"wind_speed_max": "14.1",
"sunshine_count": "0",
"sunshine_cum": "19286",
"wind_direction_max": "18"
}, {
"dateTimeRead": "2013-11-14 11:30:32",
"rain_value": "0.00",
"rain_intensity": "0.0",
"air_pressure": "1002.02",
"wind_speed": "8.9",
"air_humidity": "68.6",
"solar_radiation": "-239488.50",
"wind_direction": "322",
"air_temperature": "30.2",
"rain_cum": "237.55",
"soil_moisture1": "8.91",
"soil_temperature1": "28.5",
"soil_moisture2": "6.72",
"soil_temperature2": "27.6",
"rain_duration": "0",
"wind_speed_max": "15.1",
"sunshine_count": "455",
"sunshine_cum": "19286",
"wind_direction_max": "10"
}, {
"dateTimeRead": "2013-11-14 11:15:32",
"rain_value": "0.00",
"rain_intensity": "0.0",
"air_pressure": "1002.02",
"wind_speed": "10.2",
"air_humidity": "67.8",
"solar_radiation": "251642.70",
"wind_direction": "333",
"air_temperature": "31.0",
"rain_cum": "237.55",
"soil_moisture1": "8.90",
"soil_temperature1": "28.4",
"soil_moisture2": "7.01",
"soil_temperature2": "27.6",
"rain_duration": "0",
"wind_speed_max": "18.3",
"sunshine_count": "900",
"sunshine_cum": "18831",
"wind_direction_max": "9"
}]
}]
I have a following json string:
[ { id: '123', name: 'bla bla', type: 'Source', isLeaf: true },
{ id: '3425', name: 'test test', type: 'Reference', isLeaf: false },
{ id: '12678', name: 'tags', type: 'Source', isLeaf: false },
]
I am trying to parse this using JsonSlurper but getting error:
groovy.json.JsonException: Lexing failed on line: 1, column: 5, while reading 'i', no possible valid JSON value or punctuation could be recognized.
How do I parse it and access the id:'3425'?
Your Json is invalid, you need to use double quote to delimit strings and you also need to put quotes around the keys in your Json like so:
[ { "id": "123", "name": "bla bla", "type": "Source", "isLeaf": true },
{ "id": "3425", "name": "test test", "type": "Reference", "isLeaf": false },
{ "id": "12678", "name": "tags", "type": "Source", "isLeaf": false },
]
You can then do:
def ids = new groovy.json.JsonSlurper().parseText( json ).id
assert ids[ 1 ] == '3425'