插入mongodb时是否可以定义密钥 [英] Is it possible to define the key when inserting into mongodb

查看:107
本文介绍了插入mongodb时是否可以定义密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:在此MongoDB库中使用CodeIgniter.

Background: Using CodeIgniter with this MongoDB library.

这是我与mongodb的第一次合作,到目前为止,我很喜欢.我花了一段时间将自己从sql思维方式中分离出来,但这非常适合我当前的项目.

This is my first go-round with mongodb and I'm enjoying it thus far. It's taken a while for me to separate myself from the sql way of thinking, but it is a perfect fit for my current project.

我正在尝试使用...将数组推入文档中

I'm trying to push an array into a document using...

$this->mongo_db->where(array('_id'=>$estimate_id))->push("measurements", $newData)->update('estimates');

如果我使用json_encode($newData)对$ newData进行编码,则会得到{"levels":[{"level_qty":12,"level_uom":"ft"}]}

If I encode $newData using json_encode($newData) I get {"levels":[{"level_qty":12,"level_uom":"ft"}]}

问题是,当我的函数在mongodb文档中创建measurements行时,它会自动以我在[0]处插入的位置启动一个数组.这样...

The problem is, when my function creates the measurements line in the mongodb document, it automatically starts an array with my insertion at [0]. Like this...

"measurements" : [ { "levels" : [ { "level_qty" : 12, "level_uom" : "ft" } ] }]

...留给我...

...leaving me with...

-measurements
--0
----levels
-----0
------level_qty => 2,
------level_uom => ft

我真正想要的是...

What I really want is...

-measurements
--levels
---0
----level_qty => 2,
----level_uom => ft

我可以肯定我缺少一些基本的东西(即与php有关且与mongodb不相关),但是我是一个公认的业余爱好者,涉水太深了.

I'm certain I'm missing something fairly elementary (i.e. php related & not mongodb related), but I'm an admitted amateur who has waded too deep.

推荐答案

$ push 用于将值附加到数组.在您的示例中,measurements是一个数组,Mongo将$newData附加为第一个元素.这说明了measurementslevels之间的0索引.在您想要的结果中,measurements是与$newData等效的对象(即,它具有levels属性,而该属性又在其中包含对象数组).

$push is used to append a value to an array. In your example, measurements is an array and Mongo is appending $newData as its first element. This explains the 0 index between measurements and levels. In your desired result, measurements is an object equivalent to $newData (i.e. it has a levels property, which in turn has an array of objects within).

以下任何一个示例都可以完成您想要的操作:

Either of the following examples should accomplish what you want:

// if $newData is {"levels": [{"level_qty":12,"level_uom":"ft"}]}
->set("measurements", $newData)

// if $newData is [{"level_qty":12,"level_uom":"ft"}]
->set("measurements.levels", $newData)

// if $newData is {"level_qty":12,"level_uom":"ft"}
->push("measurements.levels", $newData)

注意:如果要在将来的更新中附加数据,$push将会更加灵活,而$set会自然覆盖给定字段.

Note: $push is going to be more flexible if you want to append data with future updates, whereas $set will naturally overwrite the given field.

这篇关于插入mongodb时是否可以定义密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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