MongoDb插入或添加到嵌入式文档中 [英] MongoDb insert or add in embedded document
问题描述
这是我的最终文档结构.我使用的是 mongo 3.0 .
{
_id: "1",
stockA: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
stockB: [ { size: "S", qty: 27 }, { size: "M", qty: 58 } ]
}
我正在将元素随机添加到stockA
或stockB
集合中.
我想提出一个满足以下规则的查询:
- 如果
item
不存在-创建整个文档,然后在stock A or B
集合中插入项目. - 如果存在
item
,但缺少stock A or B
集合,则创建stock
集合,并在集合内添加element
. - 如果存在
item
并且存在stock
集合,只需在集合内部附加element
.
问题:是否可以在一个查询中实现所有这些目的?我对当前插入件的主要要求是必须非常快速和可扩展.
如果是,请您帮我提出必要的查询.
如果否,请您指导我如何以最快,最干净的方式达到要求.
感谢您的帮助!
您要查找的操作员是 $addToSet
或 $push
与 upsert:true
组合.. >
两个运算符都可以采用多个键/值对.然后,它将对每个键分别进行操作.两者都将在尚不存在的情况下创建该数组,并且在两种情况下都将添加该值.
区别在于$ addToSet将首先检查数组中是否已存在相同的元素.当性能成为问题时,请记住MongoDB必须执行线性搜索才能做到这一点.因此,对于非常大的数组,$ addToSet可能变得很慢.
更新功能的upsert:true
选项将导致在找不到文档时创建该文档.
This is my final document structure. I am on mongo 3.0.
{
_id: "1",
stockA: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
stockB: [ { size: "S", qty: 27 }, { size: "M", qty: 58 } ]
}
I am randomly adding elements inside stockA
or stockB
collections.
I would like come up with a query which would satisfy following rules:
- If
item
is not exist - create whole document and insert item instock A or B
collection. - If
item
is exist butstock A or B
collection is missing createstock
collection and addelement
inside collection. - if
item
is exist andstock
collection is exist just appendelement
inside collection.
Question: Is it possible to achieve all that in one query? My main requirement that current insert has to be extremely fast and scalable.
If yes, could you please help me to come up with required query.
If no, could you please guide me how do I achieve requirements in fastest and cleanest way.
Thanks for any help!
The operator you are looking for is $addToSet
or $push
in combination with upsert:true
.
Both operators can take multiple key/value pairs. It will then operate separately on each key. Both will create the array when it doesn't exist yet, and in either case will add the value.
The difference is that $addToSet will first check if an identical element already exists in the array. When performance is an issue, keep in mind that MongoDB must perform a linear search to do this. So for very large arrays, $addToSet can become quite slow.
The upsert:true
option to the update function will result in the document being created when it isn't found.
这篇关于MongoDb插入或添加到嵌入式文档中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!