I'm new in mongoDB, I saw enough examples but most show how to work with collections.
I have followed data stored in mongoDB under DB name myDB:
"_id" : "some_table_name",
"content" : [{
"id" : "1",
"loctype" : "Clinic/Hospital",
"locname" : "KKH"
}, {
"id" : "2",
"loctype" : "Clinic/Hospital",
"locname" : "Singapore National Eye Centre"
}
}]
}
As you can see the model contains _id and content, where content is list of objects:
... ,
{
"id" : "ZZZ",
"loctype" : "ZZZ",
"locname" : "ZZZ"
},
...
PHP
$m = new MongoClient(/* ... */);
$db = $m->myDB;
$collection = $db->coll;
How can I fetch in PHP list of ids? a.e [1,2] in my case.
For sure I can get all model and extract ids but I try to do it stright from mongoDB.
Thanks.
It depends on how you want this formatted but here is a aggregation version which formats it in a nice way:
$mongo->collection->aggregate(array(
array('$unwind'=>'$content'),
array('$project'=>array('_id'=>'$content.id'))
))
It will print documents like:
[
{_id:1},
{_id:2}
]
Another way could be to just project the single field out with $db->collection->find(array(),array('content.id'=>1))
I should note though, it would most likely to better to just do this in PHP. Through PHP is the only way you can get the exact output you are seeking I believe.
Try this:
$collection = new MongoCollection($db, 'collection_name');
$query = array(
// Some restrictions can be here
);
$ids = array();
$cursor = $collection->find($query);
foreach ($cursor as $doc) {
$doc = (array) $doc;
$ids[] = $doc["id"];
}
var_dump($ids);
Use mapreduce followed by distinct, as follows:
mr = db.runCommand({
"mapreduce" : "things",
"map" : function() {
for (var key in this) { emit(key, null); }
},
"reduce" : function(key, stuff) { return null; },
"out": "things" + "_keys"
})
db[mr.result].distinct("_id")
["foo", "bar", "baz", "_id", ...]
Or use Variety...
Related
I have a Yii2 mongodb's collection that looks like this:
{
"_id" : "123",
"books" : [
{
"author" : "John",
"title" : "The Book"
},
{
"author" : "Smith",
"title" : "Something!"
}
]
}
{
"_id" : "321",
"books" : [
{
"author" : "John",
"title" : "The Book"
}
]
}
...
And I want to get an array of all books (an array of arrays basically):
[
{
"author" : "John",
"title" : "The Book"
},
{
"author" : "Smith",
"title" : "Something!"
},
{
"author" : "John",
"title" : "The Book"
}
...
]
I saw answers to close questions, but they all achieve something a bit different.
Also tried $collection->distinct('books', [], []) and it worked, but it removed duplicates which is unacceptable.
Use this MongoDB query to get this resultset
db.collection.aggregate([
{ $unwind : "$books"},
{ $group: {
_id: null,
items:
{ $push: "$books" }
}}
]);
Let's try like this way using foreach()?
<?php
$json = '[{"_id":"123","books":[{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"}]},{"_id":"321","books":[{"author":"John","title":"The Book"}]}]';
$array = json_decode($json, 1);
$ids = [];
foreach($array as $v) {
foreach($v['books'] as $book){
$books[] = $book;
}
}
echo json_encode($books);
?>
Output:
[{"author":"John","title":"The Book"},{"author":"Smith","title":"Something!"},{"author":"John","title":"The Book"}]
DEMO: https://3v4l.org/hdJ8H
is it possible to group/rearrange JSON output from laravel ? i want to group it before it send to view by system, so i need it to be done in server side not client side.
Lets said i have JSON structured like this :
id, name, date
or in example, is like this :
[[
{"id" : "1", "name" : "A", "date" : "2017-01-01"},
{"id" : "2", "name" : "B", "date" : "2017-01-01"},
{"id" : "3", "name" : "C", "date" : "2017-01-01"},
{"id" : "4", "name" : "D", "date" : "2018-01-01"},
{"id" : "5", "name" : "E", "date" : "2018-01-01"},
]]
is it possible to group it to be something like this ?
[
{"2017-01-01":[
{"id":"1","name":"A"},
{"id":"2","name":"B"},
{"id":"3","name":"C"}
]},
{"2018-01-01":[
{"id":"4","name":"D"},
{"id":"5","name":"E"},
]},
]
(In case you need to look my JSON Controller) This is my JSON Controller :
public function harga($id)
{
$harga = harga::whereHas('produk', function ($query) use($id) {
$query->where('id',$id);
})->get();
return response()->json([$harga],200);
}
Thanks !
use groupBy on your query:
public function harga($id)
{
$harga = harga::whereHas('produk', function ($query) use($id) {
$query->where('id',$id);
})->get()->groupBy(column_name_you_want_to_group_by);
return response()->json([$harga],200);
}
You can use groupBy method to do it:
return response()->json($harga->groupBy('date'), 200);
In Controller it is possible to do that as below
js = "your json";
$jsArray = json_decode($js, true);
$jsArray = $jsArray[0];
$newJsArr = [];
foreach ($jsArray as $j) {
$newJsArr[$j['date']][] = ["id" => $j['id'], "name" => $j['name']];
}
$newJsArr = json_encode([$newJsArr]);
I got this kind of document:
{
"_id" : ObjectId("54ad5c3b9a703a3c088b4567"),
"hard" : 750,
"coordinates" : {
"x" : 0.2388169910939489,
"y" : 0.7996551291084174
},
"indicator" : 500,
"networkIdList" : {
"networkIdData" : [
{
"networkId" : "abc123",
"type" : "SomeNetwork"
},
{
"networkId" : "123asdf",
"type" : "AnotherNetWork"
},
{
"networkId" : "abc123",
"type" : "OneMoreNetwork"
}
]
}
}
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork".
I have tried With this instruction:
$this->documentManager->createQueryBuilder('Mydocument') ->field('networkIdList.networkIdData.$.networkGamingId')->equals('abc123') ->field('networkIdList.networkIdData.$.type')->equals('')
->getQuery()
->execute());
But the cursor return no data.
I also try with
->where("function() {return this.networkIdList.networkIdData.$.networkGamingId == 'abc123'}")
but in this case i got an error that says the Object $ has no propierties.
And I need to perform a query to find the document that have "networkId" = "abc123" AND "type" = "SomeNetwork"
$qb = $dm->createQueryBuilder('Foo')
->field('networkIdList.networkIdData.networkId')->equals('abc123')
->field('networkIdList.networkIdData.type')->equals('SomeNetwork');
I understand how to parse json with PHP, however I don't understand how to read it with the eye. Can someone please help me understanad this?
Here is my code
<?php
$json = file_get_contents('json.txt');
$json_output = json_decode($json);
foreach ( $json_output->query as $stf )
{
echo "{$stf->response->domains->name}\n";
}
?>
Here is a sample of the json result
{ "query" : { "host" : "test.com",
"tool" : "pro"
},
"response" : { "domain_count" : "13",
"domains" : [ { "last_resolved" : "2012-01-11",
"name" : "test1.com"
},
{ "last_resolved" : "2012-01-11",
"name" : "test2.com"
},
As you can see I tried query->response->domains->name and it didn't work.
How would I tried name?
Thank you in advance
query->response->domains is an indexed array, so you need to get an index, say [0], and then get the ->name from that.
echo $stf->response->domains[0]->name."\n";
foreach ( $json_output->query->response->domains as $domain )
{
echo $domain->name;
}
Study this http://json.org/
If you're trying to read it by eye, it might help to reformat:
{
"query" : {
"host" : "test.com",
"tool" : "pro"
},
"response" : {
"domain_count" : "13",
"domains" : [{
"last_resolved" : "2012-01-11",
"name" : "test1.com"
},{
"last_resolved" : "2012-01-11",
"name" : "test2.com"
}]
}
}
In the model:
public function groups($getGroupId) {
$cols = array('group_id','name');
$sql = $this->select ()
->from ( $this->_name, $cols )
->where ( 'parent_id=?', $getGroupId );
$groupDetails = $this->fetchAll ( $sql );
//$childGroupName = $groupDetails['name'];
return $groupDetails->toArray();
}
groupDetails.php page:
$dbGroup = new dbGroups();
$groupDetails = $dbGroup -> groups($getGroupId);
$jsonResponse = json_encode($groupDetails);
When printing the jsonResonse (print_r($jsonResponse)). I'm getting response like this
[{"group_id":"2","name":"ABCD"},{"group_id":"7","name":"XYZ"}]
how to generate a jstree using json response
By jstree demo i written a code like this for getting tree structure but i am unable to get a tree.
Please help me
jQuery(document).ready(function(){
//alert("get tree view");
jQuery("#treeView").jstree({
// This example uses JSON as it is most common
"json_data" : {
// This tree is ajax enabled - as this is most common, and maybe a bit more complex
// All the options are almost the same as jQuery's AJAX (read the docs)
"ajax" : {
// the URL to fetch the data
"url" : "groupDetails.php",
// the `data` function is executed in the instance's scope
// the parameter is the node being loaded
// (may be -1, 0, or undefined when loading the root nodes)
"data" : function (n) {
// the result is fed to the AJAX request `data` option
return {
"operation" : "get_children",
"id" : n.attr ? n.attr("id").replace("node_","") : 1
};
}
}
},
"ui" : {
"select_limit" : 1
},
"themes" : {
"theme" : "default",
"dots" : true,
"icons" : true
},
"types" : {
// I set both options to -2, as I do not need depth and children count checking
// Those two checks may slow jstree a lot, so use only when needed
"max_depth" : -2,
"max_children" : -2,
// I want only `drive` nodes to be root nodes
// This will prevent moving or creating any other type as a root node
"valid_children" : [ "drive" ],
"types" : {
// The default type
"default" : {
// I want this type to have no children (so only leaf nodes)
// In my case - those are files
"valid_children" : "none",
// If we specify an icon for the default type it WILL OVERRIDE the theme icons
"icon" : {
"image" : "./file.png"
}
},
// The `folder` type
"folder" : {
// can have files and other folders inside of it, but NOT `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./folder.png"
}
},
// The `drive` nodes
"drive" : {
// can have files and folders inside, but NOT other `drive` nodes
"valid_children" : [ "default", "folder" ],
"icon" : {
"image" : "./root.png"
},
// those prevent the functions with the same name to be used on `drive` nodes
// internally the `before` event is used
"start_drag" : false,
"move_node" : false,
"delete_node" : false,
"remove" : false
}
}
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu" ]
})
});
Your json should look like this:
[
{
"data" : {
"icon" : <optional>,
"title" : <node name>
},
"attr" : {
"rel" : <the type you defined in the js (maybe "group")>,
"title" : <node title>,
"id" : <the node's id / group id>
},
"state" : "closed"
}
]
You can put anything you want at the "attr" hash, basically it can hold other information you might need.