使用Javascript从MongoDB返回值中提取值。

时间:2016-03-07 22:44:00

标签: javascript mongodb stored-procedures javascript-objects

在Javascript中从MongoDB查询的返回中提取整数。

我计划使用javascript中的存储过程为MongoDB设置创建一些服务器端处理的查询。作为概念验证,我试图完成从Mongo shell中现有测试数据库中提取值的步骤,使其可以在javascript中进行处理。

我的数据库包含一个条目,其中包含一个域名,以及它看到的点击次数:

{"dom":"domain1.org", "hits": 38}
{"dom":"domain2.com", "hits": 12}

为了概念证明,我想编写一个函数&addfumainHits'这将做以下事情:

db.eval('addDomainHits("domain1.org","domain2.com")');
50

[注1:我完全清楚我可以使用MongoDB聚合来执行这个特定功能,但这不是答案;这只是一个概念证明;我实际上想在我实际编写的函数中做更多 lot 。]

[注2:是的,这是非常不安全的,并且对代码注入开放。我稍后会处理。再次,这只是概念证明。]

所以,我试图将整数值放入MongoDB Shell中的一个变量中,这就是我遇到问题的地方。

$ 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 }

现在,我希望得到' 38'变成简单的整数变量,所以我可以做类似的处理:

> a=2
2
> b=3
3
> a+b
5

但是,没有快乐:

> 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
>

请注意,没有返回任何值

轻微的变种:

> 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
>

所以,在这个例子中,我怎样才能得到一个简单的' 38'变成一个变量?

1 个答案:

答案 0 :(得分:3)

如果每个domain有一条记录,请使用findOne方法

var hits = db.test_collection.findOne({dom:"seagoedd.org"},
                                   {hits:true,_id:false})["hits"];

这是有效的,因为此方法返回单个文档。而find会将cursor返回到结果列表。

注意:如果没有匹配的记录,findOne方法会返回null。在这种情况下,下面会更有意义:

var record = db.test_collection.findOne({dom:"seagoedd.org"},
                                   {hits:true,_id:false})
var hits = record?record["hits"]:0;