MongoDB, PHP and JavaScript - javascript

I have the following document in a MongoDB 2.0.4 and PHP 5.5*
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
Using php I want to create another collection having a copy of this document.Because I cannot use php mongo::command I am just getting a cursor for the first collection and insert this cursor into the second:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection is the original and $result is the new one.
Now the strange thing is sometimes this works perfectly and sometimes I recieve the following:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
And this is really bad because I am trying to get those infos into Javascript and therefore the first one (the original) is an Array whereas the second one is an object with properties.
Does somebody know why I get this and how to fix it?
So this is the solution I am using now!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));

You can copy a collection on the server with the .copyTo() method for the collection:
db.collection.copyTo("new")
There is no client transfer as there is currently being done by iterating.
If for some reason you want this to be a part of your code then there is the "runCommand" option which has a longer syntax. So in PHP code, do the longer version of this with "eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
That will run the copy on the server. Take care to read the documentation and warnings on db.eval(). And aside from all else, but much the same as you were doing, then you must re-create all indexes on the target collection that you want to use.
But in general this will be a better way than iterating over a client connection.

Have you tried to sort the cursor like:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
You might also try more of the MongoCursor options listed here:
http://www.php.net/manual/en/class.mongocursor.php at the table of contents

Related

How to add an object as a data attribute

Using the api I was able to retrieve the info i needed trough the following endpoints and create the following object.
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
}
<datagrid id = "topicGrid" data='[{}]'>
<datagrid-column head="Topic" content-key="name"></datagrid-column>
<datagrid-column head="Followers" content-key="followers"></datagrid-column>
<datagrid-column-time head="Created" content-key="created" format="date"></datagrid-column-time>
<datagrid-column-time head="Updated" content-key="updated" format="date"></datagrid-column-time>
</datagrid>
I would like to somehow append the "lego" object in the new data attribute ?
Now i tried something like
setAttribute("data", lego); but my knowledge here is limited.
Any help is apreciated. Thank you.
Update:
I tried passing the object as a string but I only get the last element of the object. Kind of like it's looping trough the whole object and stopping at the last one.
$('datagrid').attr('data', JSON.stringify(lego));
My solution
$.get( "..." ).done(function( data ) {
var legoArr = []
$.each(data.topics, function(index,item) {
var lego = {
"name" : item.name,
"followers" : item.follower_count,
"created" : item.created_at,
"updated" : item.updated_at
};
legoArr.push(lego);
});
$('datagrid').attr('data', JSON.stringify(legoArr));
});

Retrieve data from Firebase using Google Apps Script

I'm developing a Google Spreadsheet to manage reservations for a hotel. It has two main tabs. One of them is used to make the reservations and the other one is used to make queries to the reservations already made. I managed to make it work just fine with the built-in tools of google apps script using a tab as database.
I'm trying to export my data to a Firebase database, but I cannot find how to fetch some information I need. My data is stored using a code generated using the date of the reservation as integer format + the name of the person without spaces. This is the JSON generated by firebase:
{
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
}
}
My question is: let's suppose I want to know all the reservations made for the day 01/March/2021, what is the code for me to look inside the objects and then, if they match my search, get the info I need?
I converted the JSON to an array of objects, then filtered by date. Added the console logs to check if everything is right. You can see the logs when you go to view -> executions in your script. Click on the function execution to see the logged objects.
function myFunction() {
var a ={
"44256001LarissaMeimbergBaraldi" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Larissa Meimberg Baraldi"
},
"44256001ÍcaroNovodeOliveira" : {
"code" : 44256001,
"date" : "2021-03-01T03:00:00.000Z",
"name" : "Ícaro Novo de Oliveira"
},
"44256002ÍcaroNovodeOliveira" : {
"code" : 44256002,
"date" : "2021-04-01T03:00:00.000Z",
"name" : "Ícaro Dovo de Oliveira"
}
};
var values_a = Object.values(a);
var keys_a = Object.keys(a);
var array_a = keys_a.map((item, index)=> {return {"key": item, "values": values_a[index]};});
console.log(array_a);
var filter_date = "2021-03-01T03:00:00.000Z";
var filtered_a=array_a.filter(item => {return item.values.date === filter_date;})
console.log(filtered_a);
}
Thank you for your help! But my point was actually a little bit different, maybe I wasn't so clear.
While trying to explain it to you, I found the answer to my question. It was right under my nose this whole time and I didn't notice it. Here is the solution I needed:
First, I have to assign a rule to my firebase telling it what element I will be working on, so if I want to find reservations based on the date, it would look like this:
{
"rules": {
".read": true,
".write": true,
".indexOn":["date"]
}
}
Then, back to my script, it will be like:
function getReservations() {
var ss = SpreadsheetApp.getActive().getSheetByName('Search');
var date = ss.getRange('C11').getValue();
var firebaseUrl = "https://script-examples.firebaseio.com/";
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl);
var queryParameters = {orderBy:"date", equalTo: date};
var data = base.getData("", queryParameters);
for(var i in data) {
Logger.log(data[i].code, data[i].name, data[i].date);
}
}
The log retrieves:
[20-12-08 11:30:33:696 BRT] 44256001 Larissa Meimberg Baraldi 2021-03-01T03:00:00.000Z
[20-12-08 11:30:33:698 BRT] 44256001 Ícaro Novo de Oliveira 2021-03-01T03:00:00.000Z
This information was described on the documentation here:
https://sites.google.com/site/scriptsexamples/new-connectors-to-google-services/firebase/tutorials/read-and-write-data-in-firebase-from-apps-script
I think I got a little overwhelmed with the amount of information I got and skipped this part of the tutorial.
Thank you so much for your time and help.

How do I to target a single value in firebase database?

I'm having trouble figuring out how to target a single object in the firebase database. For example, I want to have a specific word/definition shown when I click an index card. I'm using this to store the data:
wordVal = $("#word").val();
defVal = $("#def").val();
data = firebase.database().ref("indexCards");
data.push( { 'word': wordVal, 'definition': defVal } );
and this to retrieve it:
data.on("child_added", function(snapshot){
console.log(snapshot.val().word);
console.log(snapshot.val().definition);
});
This gives me the whole list of words and definitions. I want to refer to specific words and specific definitions, separately. The docs say that I can reference the specific values by doing this - firebase.database().ref("child/path").
But my question is...how can I reference the path when the parents are those random numbers and letters (see below)? I know that these are unique IDs generated by firebase, but I don't know how to access them like I'd access ordinary objects.
{
"-KQIOHLNsruyrrnAhqis" : {
"definition" : "person, place, thing",
"word" : "noun"
},
"-KQIOO7Wtp2d5v2VorqL" : {
"definition" : "device for photos",
"word" : "camera"
},
"-KQISp4WMnjABxQayToD" : {
"definition" : "circus act",
"word" : "clown"
},
"-KQITC9W1lapBkMyiL7n" : {
"definition" : "device used for cutting",
"word" : "scissors"
}
}
You can use a query like this:
data = firebase.database().ref('indexCards').orderByChild('word').equalTo('noun')
It is self-explanatory, we get reference to indexCards where value of key word is equal noun, so it will return object with key -KQHZ3xCHTQjuTvonSwj
Link to Firebase docs: Retrieve data - Sorting and Filtering data
You need to put the initial push into an object then call the object later. ie
To PUSH data:
firebase.database().ref().push( { 'word': wordVal, 'definition': defVal } )
To UPDATE data or call it later:
firebase.database().ref("indexCards").set({})
or in this case:
data.set({})

Firebase (nosql) checking if key contains substring

So after building a chat app with angularjs and PHP I realized it was horrible for server performance and decided to give firebase a try using angularjs to talk with firebase(angularfire) right now I have hit a little roadblock and can't seem to figure out how to accomplish displaying a users chat rooms he's apart of. Please note this is my FIRST time using NoSql structure.
Currently my structure is like so:
{
"-K4KXS4k3mftFMe7jy_g" : {
"members" : {
"guest:Aaaa1aa" : {
"user1" : "Aaaa1aa",
"user2" : "guest"
}
},
"messages" : {
"guest:Aaaa1aa" : {
"-K4LdBwkMe7dcshqCXxW" : {
"content" : "gg",
"from" : "Aaaa1aa"
}
}
},
"rooms" : {
"guest:Aaaa1aa" : {
"roomname" : "guestAaaa1aa",
"type" : "private"
}
}
}
}
I want to check if
members->'key'->user1 == 'Aaaa1aa'
but the way I construct the key for each members data(from room key) is passed two parameters when the user clicks on 'message'(creates new room or opens existing room) in another function and that is their user name and the users profile name they clicked on. hence the keys with the delimiter ':' (guest:Aaaa1aa).
So my question is can I check if the members key contains a substring value ? sort of like explode in PHP.
What I want my query to be like:
select uniqueid(room_name) from members where user1 = 'passed value'
and if above is possible would the below be possible as well ?
select uniqueid(room_name) from members where user1 = 'passed value' || user2 = 'passed value'
thanks for any help, if I am structuring this wrong please let me know and point me into the right direction.

javascript or jquery: Looping a multidimensional object

I just started playing around with JSON and I have created this example.
var shows = {
"ShowA":
{ "Date" : "November 3-5, 2011",
"Phone" : "111-111-1111",
"Location" : "some location",
"url" : "http://www.showA.com"
},
"ShowB":
{ "Date" : "January 15-18, 2012",
"Phone" : "222-222-2222",
"Location" : "another location",
"url" : "http://www.showB.com"
}
};
I figured out how to access each bit of information...ie: alert(shows.ShowA.Date);
However, I can't figure out how to loop the entire shows object in order alert each show and each show's properties. Do I need to change it to an array?
Any help would be greatly appreciated.
you can use a for ... in loop:
for(var key in shows) {
if (shows.hasOwnProperty(key)) {
alert(shows[key].Date);
}
}
It's important to note that an object has no sort order, but an array does. So if you wanted to sort by dates, you would need to use an array.
Also it's good practice to use Object.hasOwnProperty
for(show in shows){
console.log(shows[show]);
}
Fiddle: http://jsfiddle.net/maniator/Wp3N9/
No extra libraries needed ^_^

Categories

Resources