从PHP插入时在MongoDB上执行JS [英] Executing JS on MongoDB when inserting from PHP

查看:113
本文介绍了从PHP插入时在MongoDB上执行JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用mongo shell时,我可以运行以下命令:

When using mongo shell I can run something like this:

db.sandbox.insert({"line" : db.eval('storedFunction()') })
       or
db.sandbox.insert({"line" : function() {return 1337} })

我无法使用php达到相同的效果. 我想做的是运行类似于

I was unable to achieve the same effect using php. What I wish to do is run something similar to

$fnc = "function() {return 123}";
$col = (new Mongo)->database->collection;
$col->insert(['col' => new MongoCode($fnc)]);

找到

{
   "_id" : ...., 
   "col" : 123
} 

集合中的

.我怎样才能做到这一点?可能吗?


如果您想要更多细节,我正在尝试模仿自动增量.我正在编写的此函数应检索增量字段的最后使用的值,将其递增并返回该值,从而为要插入的文档分配唯一的值.

in the collection. How can I achieve this? Is it even possible?


If you want even more details I'm trying to imitate autoincrement. This function that I'm writing should retrieve the last used value of incremental field, increment it and return the value thus assigning a unique value to the document that is being inserted.

推荐答案

您完全无法使用MongoDB做您想做的事情.在shell中运行示例时,它首先调用db.eval...位,然后将计算结果作为文档的一部分传递. Mongo在写操作期间唯一要评估的是特殊修饰符字段,作为更新的一部分(或者,如果需要,可以是upsert).但是,这些都不能让您做一个每个收集的计数器.

You can't do what you want with MongoDB, exactly. When you run your example in the shell, it calls the db.eval... bit first, then passes the computed result as part of the document. The only thing Mongo will evaluate during a write operation are the special modifier fields as part of an update (or upsert, if you want). None of those will let you do a per-collection counter, though.

对于自动增量,您需要执行两个查询.您可以使用findAndModify原子地递增并检索一个数字,然后将其分配给您的lines值.

For autoincrement, you'll need to do two queries. You can use findAndModify to atomically increment and retrieve a number, then assign it to your lines value.

这是您要从shell中执行的操作:

Here's how you'd do it from the shell:

counter = db.counters.findAndModify({
  query: {_id: "line-counter"}, 
  update: {$inc: {value: 1}}, 
  new: true, 
  upsert: true}).value
db.sandbox.insert({line: counter})

这篇关于从PHP插入时在MongoDB上执行JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆