|
这个系列主要作mongodb的备忘.
之前在其他地方写的东西也慢慢迁移过来. 这些内容基本上就是从官网文档开始扩展.
这一篇主要记录mongo的update.
首先有若干的operator, update的operator有:
$inc: 就是加了
db.products.update( { sku: "abc123" }, { $inc: { quantity: 5 } } )
$mul:就是乘
db.products.update( { _id: 1 }, { $mul: { price: 1.25 } } )
$rename
db.students.update( { _id: 1 }, { $rename: { 'nickname': 'alias', 'cell': 'mobile' } } )
$setOnInsert 发生在upsert发生insert时
db.products.update(
{ _id: 1 },
{ $setOnInsert: { defaultQty: 100 } },
{ upsert: true }
)
$set和$unset
db.products.update(
{ sku: "abc123" },
{ $set: { quantity: 500, instock: true, "details.make": "ZYX" } }
)
unset删除一个field,后面跟的值不影响.
db.products.update( { sku: "unknown" },
{ $unset: {
quantity: "",
instock: ""
}
}
)
$min和$max
min就是更新为指定值和当前值的min, max反之.
$currentdate
直接设为当前时间
基本的update oprator就是这些了,是不是很简单
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
考虑到文档的嵌套结构,情况就有点麻烦了.
首先看一下嵌套文档的情况:
db.inventory.find(
{
producer:
{
company: 'ABC123',
address: '123 Street'
}
}
)
db.inventory.find( { 'producer.company': 'ABC123' } )
这是单纯的嵌套文档.这两种方法都可以.
如果存在array,array里面又有嵌套文档.情况又不一样了
dot-notation
先看简单的array的情况:
假设有如下doc
{ _id: 5, type: "food", item: "aaa", ratings: [ 5, 8, 9 ] }
{ _id: 6, type: "food", item: "bbb", ratings: [ 5, 9 ] }
{ _id: 7, type: "food", item: "ccc", ratings: [ 9, 5, 8 ] }
那么:
db.inventory.find( { ratings: 5 } ) 会找出 rating中包含5的.
db.inventory.find( { 'ratings.0': 5 } )会找出第一个元素是5的.
db.inventory.find( { ratings: { $elemMatch: { $gt: 5, $lt: 9 } } } ) 使用elemmatch要求rating至少一个元素满足所有后面的条件.比如1和3中,是有8可以满足
db.inventory.find( { ratings: { $gt: 5, $lt: 9 } } )没有使用elemmatch,则要求rating中元素的组合可以满足所有后面的条件. 1,2,3都满足.
现在看一下比较复杂的情况, array中包含嵌套文档:
考虑如下doc:
{
_id: 100,
type: "food",
item: "xyz",
qty: 25,
price: 2.5,
ratings: [ 5, 8, 9 ],
memos: [ { memo: "on time", by: "shipping" }, { memo: "approved", by: "billing" } ]
}
{
_id: 101,
type: "fruit",
item: "jkl",
qty: 10,
price: 4.25,
ratings: [ 5, 9 ],
memos: [ { memo: "on time", by: "payment" }, { memo: "delayed", by: "shipping" } ]
}
那么
db.inventory.find( { 'memos.0.by': 'shipping' } ) 查找memos第一个元素的by是shipping的
db.inventory.find( { 'memos.by': 'shipping' } ) 查找memos有元素的by是shipping的
使用elemmatch和不使用emelmath的情况如前所示.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
array在mongo是一种重要的数据结构,详细看一下它的内容.放在下一篇吧
版权声明:本文为博主原创文章,未经博主允许不得转载。 |
|