Extracting an integer from the return of a MongoDB query, in Javascript.
I'm planning to create some server-side processed queries for my MongoDB setup, using stored procedures in javascript. As Proof-of-concept, I'm trying to walk through the steps of extracting values from my existing test database in the Mongo shell, making them accessible for processing in javascript.
My database consists of entries which includes a domain name, and the number of hits it has seen:
{"dom":"domain1.org", "hits": 38}
{"dom":"domain2.com", "hits": 12}
For Proof of concept, I want to write a function 'addDomainHits' which will do the following:
db.eval('addDomainHits("domain1.org","domain2.com")');
50
[Note 1: I'm perfectly aware that I could use MongoDB aggregations to perform this particular function, but that isn't the answer; this is just a Proof of concept; I actually want to do a lot more inside the functions I actually write.]
[Note 2: Yes, this is horribly insecure, and open to code injection. I'll deal with that later. Again, this is just Proof of Concept.]
So, I tried to get the integer value into a variable in the MongoDB Shell, and that's where I run into problems.
$ mongo
MongoDB shell version: 2.6.11
connecting to: test
> use test_database
switched to db test_database
> var r=db.test_collection.find({"dom":"domain1.org"},{hits:true,_id:false})
> r
{ "hits" : 38 }
Now, I want to get the '38' into simple integer variable, so I can do processing similar to:
> a=2
2
> b=3
3
> a+b
5
but, no joy:
> r=db.test_collection.find({"dom":"domain1.org"},{hits:true,_id:false})
> r
{ "hits" : 38 }
> var r=db.test_collection.find({"dom":"domain1.org"},{hits:true,_id:false})
> r.hits
>
Notice that no value got returned
slight variant:
> var r=db.test_collection.find({"dom":"domain1.org"},{hits:true,_id:false})
> var h=r.hits
> h
>
OR
> var r=db.test_collection.find({dom:"seagoedd.org"},{hits:true,_id:false})
> var h=r['hits']
> h
>
So, in this example, how can I get a simple '38' into a variable?
.distinct()makes any attempt to return anything else ( array of values ). It is the job of your code to extract values from the returned object(s) in the way you want to use it, and not the job of the database to do such transformations.