MongoDb插入或添加到嵌入式文档中 [英] MongoDb insert or add in embedded document

查看:513
本文介绍了MongoDb插入或添加到嵌入式文档中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的最终文档结构.我使用的是 mongo 3.0 .

   {
     _id: "1",
     stockA: [ { size: "S", qty: 25 }, { size: "M", qty: 50 } ],
     stockB: [ { size: "S", qty: 27 }, { size: "M", qty: 58 } ]
   }

我正在将元素随机添加到stockAstockB集合中. 我想提出一个满足以下规则的查询:

  1. 如果item不存在-创建整个文档,然后在stock A or B集合中插入项目.
  2. 如果存在item,但缺少stock A or B集合,则创建stock集合,并在集合内添加element.
  3. 如果存在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:

  1. If item is not exist - create whole document and insert item in stock A or B collection.
  2. If item is exist but stock A or B collection is missing create stock collection and add element inside collection.
  3. if item is exist and stock collection is exist just append element 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屋!

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