MongoDB:集合中嵌套对象数组内的唯一字段 [英] MongoDB: Unique field inside a nested array of object in a collecction

查看:71
本文介绍了MongoDB:集合中嵌套对象数组内的唯一字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 mongo 集合,每个文档都包含一个嵌套的对象数组,如下所示:

<预><代码>[{ item: "journal", instock: [ { 仓库: "A", qty: 5 }, { 仓库: "C", qty: 15 } ] },{ item: "notebook", instock: [ { 仓库: "C", qty: 5 } ] },{ 项目:纸",库存:[ { 仓库:A",数量:60 },{ 仓库:B",数量:15 } ] },{ item: "planner", instock: [ { 仓库: "A", 数量: 40 }, { 仓库: "B", qty: 5 } ] },{ 项目:明信片",库存:[ { 仓库:B",数量:15 },{ 仓库:C",数量:35 } ] }]

我希望 instock 中的仓库字段对于每个项目文档都是唯一的.

示例:

{ item: "journal", instock: [ { 仓库: "A", qty: 5 }, { 仓库: "A", qty: 15 } ] }

不应插入前一条记录,因为仓库在单个文档中不是唯一的.

哪种类型的 indez 应确保此限制.

解决方案

索引的目的是加速选择查询,而不是数据验证.这个数据验证必须在应用层实现.

您必须避免使用不必要的索引,因为它会降低 MongoDB 的速度.每个索引都必须在 select 查询上检查(尝试选择获胜计划)并在文档插入/更新/删除时更新.

I have a mongo collection, each document contains a nested array of objects like the following :

[
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]

I want warehouse field inside instock to be unique with each item document.

Example:

{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "A", qty: 15 } ] }

The previous record shouldn't be inserted as warehouse is not unique withing a single document.

What type of indez should ensure this restriction.

解决方案

The indexes purpose is to speedup of the select queries, not the data validation. This data validation must be implemented in the application layer.

You must avoid the unnecessary indexes, because it slow downs MongoDB. Each index must be examinated on the select query (trying to pick the winning plan) and updated on document insert/update/delete.

这篇关于MongoDB:集合中嵌套对象数组内的唯一字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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