MongoDB:嵌入式文档中的唯一键 [英] MongoDB: Unique Key in Embedded Document

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

问题描述

是否可以为嵌入式文档中的密钥设置唯一密钥?

Is it possible to set a unique key for a key in an embedded document?

我有一个包含以下示例文档的Users集合:

I have a Users collection with the following sample documents:

 {
       Name: "Bob",
       Items: [
           {
               Name: "Milk"
           },
           {
               Name: "Bread"
           }
       ]
    },
    {
       Name: "Jim"
    },

是否可以在Items.Name属性上创建索引?

Is there a way to create an index on the property Items.Name?

尝试创建索引时出现以下错误:

I got the following error when I tried to create an index:

> db.Users.ensureIndex({"Items.Name": 1}, {unique:true});
E11000 duplicate key error index: GroceryGuruApp.Users.$Items.Name_1  dup key: {
 : null }

有什么建议吗?谢谢!

推荐答案

唯一索引仅在集合中存在.要在文档中实施唯一性和其他约束,您必须在客户端代码中执行. (可能虚拟馆藏允许这样做,您可以投票赞成.)

Unique indexes exist only across collection. To enforce uniqueness and other constraints across document you must do it in client code. (Probably virtual collections would allow that, you could vote for it.)

您要尝试做的是在键Items.Name上创建索引,该索引在任何文档中都不存在(它不引用数组Items中的嵌入式文档),因此它是null,并且违反了整个馆藏的唯一约束.

What are you trying to do in your case is to create index on key Items.Name which doesn't exist in any of the documents (it doesn't refer to embedded documents inside array Items), thus it's null and violates unique constraint across collection.

这篇关于MongoDB:嵌入式文档中的唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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