MongoDB中的唯一索引

时间:2016-06-27 01:15:21

标签: arrays json mongodb mongodb-query

有人可以帮我创建以下条件的唯一索引@ mongoDB吗?

假设我有这样的架构,我想在1.path 2.verb上有一个唯一的复合索引3.“switches.name”4。“switches.value”

ToList

所以,如果我尝试插入

Dim pointPairs = Enumerable.Range(0, points.Length - 2).
                            Select(Function(n) Tuple.Create(points(n), points(n + 1))).
                            ToArray()

我应该会出现重复错误,但如果我插入

{
  "path": "somepath",
  "verb": "GET",
  "switches": [
    {
      "name": "id",
      "value":"123"
    },
    {
      "name": "age",
      "value":"25"
    }
  ]
}

{
  "path": "somepath",
  "verb": "GET",
  "switches": [
    {
      "name": "id",
      "value":"123"
    },
    {
      "name": "age",
      "value":"25"
    }
  ]
}

我不应该有任何错误。

基本上,我应该被允许插入具有不同数组“开关”的文档。

2 个答案:

答案 0 :(得分:3)

我担心你想要实现的目标不能通过你当前的架构。

首先,您必须了解索引上的数组如何工作: https://docs.mongodb.com/manual/core/index-multikey/#multikey-indexes

  

要索引包含数组值的字段, MongoDB会为数组中的每个元素创建索引键

这表明数组不会被索引为单个对象,而是 unwinded 成多个对象。

要获得与您想要的类似的结果,您可以考虑使用对象属性贴图:

{
    "path" : "somepath", 
    "verb" : "GET", 
    "switches" : {
        "id": "123",
        "age": "25"
    }
}

并像往常一样创建唯一索引:

db.yourCollection.createIndex({"path": 1, "verb": 1, "switches": 1}, {"unique": true});

然而,这通常是不受欢迎的,因为查询密钥非常重要 (Also read about this here)

因此,您可以将数组包装在另一个对象中:

{
    "path" : "somepath", 
    "verb" : "GET", 
    "switches" : {
        "options": [
            {
                "name" : "id", 
                "value" : "123"
            }, 
            {
                "name" : "age", 
                "value" : "25"
            }
        ]
    }
}

使用相同的索引:

db.yourCollection.createIndex({"path": 1, "verb": 1, "switches": 1}, {"unique": true});

如果您打算在switches.options阵列上执行查询,这将是更理想的解决方案。

答案 1 :(得分:0)

yourDatabase.yourCollection.ensureIndex({"path": 1, "verb": 1, "switches": 1}, {"unique": true})

您可以根据需要使用ensureCollection()createCollectionhttps://docs.mongodb.com/manual/core/index-unique/

相关问题