JSON array pushing - arrays

I have this example array for an entry to be inserted to a YUI datatable
var book = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
will i be able to get the same array by doing this?
var book = [];
var booktemp = {
"id" : "po-0167"
};
book.push(booktemp);
booktemp = {
"date" : new Date(1980, 2, 24)
};
book.push(booktemp);
booktemp = {
"quantity" : 1
};
book.push(booktemp);
booktemp = {
"amount" : 4
};
book.push(booktemp);
booktemp = {
"title" : "A Book About Nothing"
};
book.push(booktemp);
what i am trying here is to write a generic method that will iterate through a list of results and able to form an entry in the future.
var resultsArray = [];
for( int i = 0; i < array.features.length; i ++)
{
var resultsFeatureArray = [];
for( att in array.features[i].attributes)
{
var temp = {
att : array.features[i].attributes[att]
}
resultsFeatureArray.push(temp);
}
resultsArray.push(resultsFeatureArray);
}
so how could i make the array the same as the first segment of the book code?
added my whole sample code, the commented book array seems to work but the uncommented part seems to not be able to show the rows
<script type="text/javascript">
YAHOO.util.Event.addListener(window, "load", function() {
YAHOO.example.Data = {
bookorders: [
]
}
var bookorders = [];
/*
var book = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
*/
var book = [];
var booktemp = {
"id" : "po-0167"
};
book.push(booktemp);
booktemp = {
"date" : new Date(1980, 2, 24)
};
book.push(booktemp);
booktemp = {
"quantity" : 1
};
book.push(booktemp);
booktemp = {
"amount" : 4
};
book.push(booktemp);
booktemp = {
"title" : "A Book About Nothing"
};
book.push(booktemp);
bookorders.push(book);
YAHOO.example.Basic = function() {
var myColumnDefs = [
{key:"id", sortable:true, resizeable:true},
{key:"date", formatter:YAHOO.widget.DataTable.formatDate, sortable:true, sortOptions:{defaultDir:YAHOO.widget.DataTable.CLASS_DESC},resizeable:true},
{key:"quantity", formatter:YAHOO.widget.DataTable.formatNumber, sortable:true, resizeable:true},
{key:"amount", formatter:YAHOO.widget.DataTable.formatCurrency, sortable:true, resizeable:true},
{key:"title", sortable:true, resizeable:true}
];
var myDataSource = new YAHOO.util.DataSource(bookorders);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
fields: ["id","date","quantity","amount","title"]
};
var myDataTable = new YAHOO.widget.DataTable("basic",
myColumnDefs, myDataSource);
return {
oDS: myDataSource,
oDT: myDataTable
};
}();
});

I tried and found the solution to it, since the att and values will be object after i push it
var temp = new Object();
temp["id"] = "po-0167";
temp["date"] = new Date(1980, 2, 24);
temp["quantity"] = 1;
temp["amount"] = 4;
temp["title"] = "A Book About Nothing";
bookorders.push(temp);
this will make it display in the datatable, the generic part will just be iterated through using the temp[att] = attributes[att];

var book = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
it's not array.
Array is
var books =[{
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
}]
and after manipulation in your example you will get next array
var book2 =[{
"id" : "po-0167"
},{
"date" : new Date(1980, 2, 24)
},{
"quantity" : 1
},{
"amount" : 4
},{
"title" : "A Book About Nothing"
}]
it's not the same.
You must do next:
var book = new Array();
var booktemp = {
"id" : "po-0167",
"date" : new Date(1980, 2, 24),
"quantity" : 1,
"amount" : 4,
"title" : "A Book About Nothing"
};
book.push(booktemp);
PS.
var arr = [] and var arr = new Array() are the same
Not all browsers works well with var arr = []

Related

Pulling Data from JSON Array to make 3 different Arrays

I'm trying to make three arrays based on the JSON Data that I'm pulling from my restaurant. I want to have an array of Entre, Main, & Dessert that will display in a tableView Object. This is the code I'm using to pull in data:
func loadMeals() {
Helpers.showActivityIndicator(activityIndicator, view)
if let restaurantId = restaurant?.id {
APIManager.shared.getMeals(restaurantId: restaurantId, completionHandler: { (json) in
if json != nil {
self.meals = []
if let tempMeals = json["meals"].array {
for item in tempMeals {
let meal = Meal(json: item)
self.meals.append(meal)
}
self.tableView.reloadData()
Helpers.hideActivityIndicator(self.activityIndicator)
}
}
})
}
}
Item prints out:
items {
"name" : "Spinach Artichoke",
"course" : "entres",
"short_description" : "savory",
"id" : 20,
"image" : "http:\/\/localhost:8000\/media\/product_images\/artichoke.jpg",
"usage" : "homestyle",
"sizes" : [
{
"size" : 3,
"id" : 24,
"product_id" : 20,
"price" : 55.899999999999999
},
{
"size" : 4,
"id" : 25,
"product_id" : 20,
"price" : 78
},
{
"size" : 5,
"id" : 26,
"product_id" : 20,
"price" : 125
}
]
}
items {
"name" : "Pizza",
"course" : "main",
"short_description" : "Melty cheese",
"id" : 19,
"image" : "http:\/\/localhost:8000\/media\/product_images\/pizza.jpg",
"usage" : "top",
"sizes" : [
{
"size" : 6,
"id" : 23,
"product_id" : 19,
"price" : 75.989999999999995
}
]
}
items {
"name" : "Chocolate Mousee Devil's cake",
"course" : "dessert",
"short_description" : "Sweet And Smooth",
"id" : 18,
"image" : "http:\/\/localhost:8000\/media\/product_images\/Devils_cake.jpg",
"usage" : "sweets",
"sizes" : [
{
"size" : 2,
"id" : 20,
"product_id" : 18,
"price" : 50
},
{
"size" : 3,
"id" : 21,
"product_id" : 18,
"price" : 120
},
{
"size" : 4,
"id" : 22,
"product_id" : 18,
"price" : 376
}
]
}
I'm trying to figure out how to create the arrays by pulling the data from this function. Any help would be appreciated.
Just You need to group By course
meals Array will be [[String:Any]] Key will be course Any will be Array of course items
func loadMeals() {
Helpers.showActivityIndicator(activityIndicator, view)
if let restaurantId = restaurant?.id {
APIManager.shared.getMeals(restaurantId: restaurantId, completionHandler: { (json) in
if json != nil {
self.meals = []
if let tempMeals = json["meals"].array {
self.meals = Dictionary(grouping: tempMeals, by: { $0["course"] as! String })
self.tableView.reloadData()
Helpers.hideActivityIndicator(self.activityIndicator)
}
}
})
}
}
OutPut Console:
["Main": [["name": Chocolate Mousee Devil's cake, "course": Main, "short_description": Sweet And Smooth, "id": 18, "image": http://localhost:8000/media/product_images/Devils_cake.jpg, "usage": sweets, "sizes": <__NSArrayI 0x60c0002456a0>(
{
id = 20;
price = 50;
"product_id" = 18;
size = 2;
},
{
id = 21;
price = 120;
"product_id" = 18;
size = 3;
},
{
id = 22;
price = 376;
"product_id" = 18;
size = 4;
}
)
]], "dessert": [["name": Chocolate Mousee Devil's cake, "course": dessert, "short_description": Sweet And Smooth, "id": 18, "image": http://localhost:8000/media/product_images/Devils_cake.jpg, "usage": sweets, "sizes": <__NSArrayI 0x60c000243d50>(
{
id = 20;
price = 50;
"product_id" = 18;
size = 2;
},
{
id = 21;
price = 120;
"product_id" = 18;
size = 3;
},
{
id = 22;
price = 376;
"product_id" = 18;
size = 4;
}
)
], ["name": Chocolate Mousee Devil's cake, "course": dessert, "short_description": Sweet And Smooth, "id": 18, "image": http://localhost:8000/media/product_images/Devils_cake.jpg, "usage": sweets, "sizes": <__NSArrayI 0x60c000248910>(
{
id = 20;
price = 50;
"product_id" = 18;
size = 2;
},
{
id = 21;
price = 120;
"product_id" = 18;
size = 3;
},
{
id = 22;
price = 376;
"product_id" = 18;
size = 4;
}
)
]]]

filter the records using loadash angularjs

var arr = Array [ Object, Object ]
into arr {
"name" : "xyz",
"age" : "22",
"sports" : Array[
{
id:1,
name : "xyz",
},
{
id:2,
name : "yyy",
},
]
}
var obj = Object { name: "JXZ", id :1};
var response = _.filter(arr, function(user) {
return user.sports.id === obj.id;
});
filter the record that match with obj's id from arr's sports.id return array object.
I'm suppose to put loop but i guess that not right solution if please
Please try this below code.
<script>
var app = angular.module('app',[]);
app.controller('ctrl',function($scope){
$scope.arr = Array [ Object, Object ];
$scope.arr = {
"name" : "xyz",
"age" : "22",
"sports" : [
{
id:1,
name : "xyz",
},
{
id:2,
name : "yyy",
}
]
}
var obj = { name: "JXZ", id :1};
var filteredSports = _.filter($scope.arr.sports, function (sport) {
return sport.id == obj.id;
})
$scope.arr.sports = filteredSports;
console.log($scope.arr);
})
</script>

Sort in mongoDB using a specific order

I am currently looking to sort the sub document, Clients, in a particular order based on an array.
The mongoDB structure is
{
"_id" : "1033",
"Name" : "Test",
"Clients" : [
{
"Id" : 1033,
"Types" : [
{
"Class" : "C",
"Service" : null
},
{
"Class" : "B",
"Service" : null
}
]
},
{
"Id" : 156136,
"Types" : [
{
"Class" : "A",
"Service" : null
},
{
"Class" : "B",
"Service" : null
},
{
"Class" : "C",
"Service" : null
},
{
"Class" : "D",
"Service" : null
}
]
}
]
}
I need the above document displayed in the order based on a array like [B, A, D, C]
So that the output would be as below:
{
"_id" : "1033",
"Name" : "Test",
"Clients" : [
{
"Id" : 1033,
"Types" : [
{
"Class" : "B",
"Service" : null
},
{
"Class" : "C",
"Service" : null
}
]
},
{
"Id" : 156136,
"Types" : [
{
"Class" : "B",
"Service" : null
},
{
"Class" : "A",
"Service" : null
},
{
"Class" : "D",
"Service" : null
},
{
"Class" : "C",
"Service" : null
}
]
}
]
}
Could you please help me on how to achieve this?
I am currently using MongoDB Driver for .Net
Custom ordering is possible via aggregation as specified here.
I've solved my problem with custom sorting , using $addFields and $indexOfArray aggregations.
let imagine that my document has two fields: BouqetId, Name
[
{ "BouqetId" : 2, "Name" : "Name2"},
{ "BouqetId" : 16, "Name" : "Name16"},
{ "BouqetId" : 25, "Name" : "Name25"},
{ "BouqetId" : 15, "Name" : "Name15"},
{ "BouqetId" : 125, "Name" : "Name125"},
{ "BouqetId" : 258, "Name" : "Name258"},
{ "BouqetId" : 127, "Name" : "Name127"}
...
]
and I want to search for Bouqet with Ids [258,15,2,16] and get them with this order.
1/ I filter my collection using $in operator in $match aggregation to get the required documents: view step one in code.
2/ I add a field using $addFields aggregation named Order and assign to it the index of the BouqetId in the searched array using $indexOfArray aggregation.
3/ finally I sort them using the newly added Order field.
4/ I get my custom-ordered result. I can remove the order field but it is ok for now.
here and exmaple in Nodejs :
var db = client.db("MyDatabase");
var collection = db.collection("Bouqets");
var pipeline = [
{
"$match": {
"BouqetId": {
"$in": [
258,
15,
2,
16
]
}
}
},
{
"$addFields": {
"Order": {
"$indexOfArray": [
[
258,
15,
2,
16
],
"$BouqetId"
]
}
}
},
{
"$sort": {
"Order": 1.0
}
}
];
var cursor = collection.aggregate(pipeline);
Here my result :
[
{ "BouqetId" : 258, "Name" : "Name258" , "Order" : 0},
{ "BouqetId" : 15, "Name" : "Name15", "Order" : 1},
{ "BouqetId" : 2, "Name" : "Name2", "Order" : 2},
{ "BouqetId" : 16, "Name" : "Name16", "Order" : 3}
]
here the same example in c# :
IMongoClient client = new MongoClient("mongodb://host:port/");
IMongoDatabase database = client.GetDatabase("MyDatabase");
IMongoCollection<BsonDocument> collection = database.GetCollection<BsonDocument>("Bouqets");
var options = new AggregateOptions()
{
AllowDiskUse = false
};
// my array
var searchArray = new int[] {258, 15, 2, 16};
PipelineDefinition<BsonDocument, BsonDocument> pipeline = new BsonDocument[]
{
new BsonDocument("$match", new BsonDocument()
.Add("BouqetId", new BsonDocument()
.Add("$in", new BsonArray(searchArray)
)
)),
new BsonDocument("$addFields", new BsonDocument()
.Add("Order", new BsonDocument()
.Add("$indexOfArray", new BsonArray()
.Add(new BsonArray(searchArray)
)
.Add("$BouqetId")
)
)),
new BsonDocument("$sort", new BsonDocument()
.Add("Order", 1.0))
};
var result = collection.Aggregate(pipeline, options).ToList();
Custom ordering is not possible in MongoDB. You can either sort ascending or descending.

Query on array of array object in mongodb

Following is my product collection in mongodb..
{
"_id" : ObjectId("56d42389db70393cd9f47c22"),
"sku" : "KNITCHURI-BLACK",
"options" : [
{
"sku" : "KNITCHURI-BLACK-M",
"stores" : [
{
"code" : "6",
"quantity" : 0
},
{
"code" : "10",
"quantity" : 26
}
],
"ean_code" : "2709502",
"size" : "M"
},
{
"sku" : "KNITCHURI-BLACK-S"
"stores" : [
{
"code" : "6",
"quantity" : 0
},
{
"code" : "10",
"quantity" : 30
}
],
"size" : "S"
}
]
}
want query on where { 'options.stores.code' : '6' } and { 'options.stores.quantity' : { $gt : 0 } }, How i query on this collection then i got response? Kindly help on this issue..
Here is the two approaches to get documents in Mongoose.
You can change the Mongo query if required as given in the various answers. I have just used your approach for Mongo query.
Approach 1 - Using cursor - Recommended Approach
Approach 2 - Using Query
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var Schema = mongoose.Schema, ObjectId = Schema.ObjectId;
var Store = new Schema({
code : String,
quantity : Number
});
var Option = new Schema({
sku : String,
stores : [ Store ],
ean_code : String,
size : String
});
var productSchema = new Schema({
_id : ObjectId,
sku : String,
options : [ Option ]
});
var Product = mongoose.model('product', productSchema, 'product');
console.log("Cursor Approach #1");
var cursor = Product.find({
'options.stores' : {
$elemMatch : {
code : '6',
quantity : {
$gt : 0
}
}
}
}).cursor();
console.log("Curosr Results***************************************");
cursor.on('data', function(doc) {
console.log("Getting doc using cursor ==========>" + JSON.stringify(doc));
});
cursor.on('close', function() {
console.log("close the cursor");
});
console.log("Query Approach #2");
var query = Product.find({
'options.stores' : {
$elemMatch : {
code : '6',
quantity : {
$gt : 0
}
}
}
});
console.log("Query Results***************************************");
query.exec(function(err, doc) {
if (err) {
console.log(err);
}
console.log("Getting doc using query ==========>" + JSON.stringify(doc));
});
I think you need to unwind options
db.product.aggregate( [
{ $unwind: "$options" }
{ $match: { 'options.stores.code' : '6','options.stores.quantity' : { $gt : 0 }}
] )
As far as I understand the question, you want to find a products that are in stock in stores with code 6. The following query does that:
db.collection.find({"options.stores" : {$elemMatch: {"code" : "6", "quantity" : {$gt : 0}}}});

MongoDB: how to group by date with mongo date aggregration using java driver

I have been struggling writing to convert a mongo shell command to java query on top of the java mongo driver in order to call it in my webapp project: the command is as follow:
db.post.aggregate(
{
$match: { dateCreated:
{
"$gt": new ISODate("2013-08-09T05:51:15.000Z"),
"$lt": new ISODate("2013-08-09T05:51:20.000Z")
}
}
},
{
$group: {
_id: {
hour: {$hour: "$dateCreated"},
minute: {$minute: "$dateCreated"},
second: {$second: "$dateCreated"}
},
cnt: {$sum : 1}
}
}
)
The query above outputs result in the format below in the mongo shell:
{
"result" : [
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 19
},
"cnt" : 26
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 18
},
"cnt" : 29
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 17
},
"cnt" : 27
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 16
},
"cnt" : 25
},
{
"_id" : {
"hour" : 5,
"minute" : 51,
"second" : 15
},
"cnt" : 16
}
],
"ok" : 1
}
I failed in writing the same query in java using java mongo driver . below is my query:
DBObject matchStart = new BasicDBObject("$match",new BasicDBObject("dateCreated",new BasicDBObject("$gt",startTime).append("$lt",endTime)));
DBObject field = new BasicDBObject("dateCreated",1);
field.put("h", new BasicDBObject("$hour","$dateCreated"));
field.put("m", new BasicDBObject("$minute","$dateCreated"));
field.put("s", new BasicDBObject("$second","$dateCreated"));
DBObject project = new BasicDBObject("$project",field);
DBObject groupField = new BasicDBObject("_id","$s");
groupField.put("count", new BasicDBObject("$sum",1));
DBObject group = new BasicDBObject("$group",groupField);
AggregationOutput output = mongoOperations.getCollection("post").aggregate(matchStart,project,group);
return output;
it returns a resultset below :
{"result" : [
{ "_id" : 19 , "count" : 26} ,
{ "_id" : 18 , "count" : 29} ,
{ "_id" : 17 , "count" : 27} ,
{ "_id" : 16 , "count" : 25} ,
{ "_id" : 15 , "count" : 16}
] ,
"ok" : 1.0}
I am having challenges making the query include the minute part and the hour part. How can tweak my query to output the same resultset as in the mongo shell one.
Thanks for looking at that
Java code for given query is as follows :
DBCollection coll = ...
Date startDate = ...
Date endDate = ...
DBObject dateQuery = new BasicDBObject();
dateQuery.put("$gt", startDate);
dateQuery.put("$lt", endDate);
DBObject match = new BasicDBObject();
match.put("dateCreated", dateQuery);
DBObject id = new BasicDBObject();
id.put("hour", new BasicDBObject("$hour", "$dateCreated"));
id.put("minute", new BasicDBObject("$minute", "$dateCreated"));
id.put("second", new BasicDBObject("$second", "$dateCreated"));
DBObject group = new BasicDBObject();
group.put("_id", id);
group.put("cnt", new BasicDBObject("$sum", 1));
AggregationOutput output = coll.aggregate(new BasicDBObject("$match", match), new BasicDBObject("$group", group));
if (output != null) {
for (DBObject result : output.results()) {
Integer count = (Integer) result.get("cnt");
DBObject idObj = (DBObject) result.get("_id");
Integer hour = (Integer) idObj.get("hour");
Integer minute = (Integer) idObj.get("minute");
Integer second = (Integer) idObj.get("second");
}
}

Resources