jjj
jjj

Reputation: 2672

How to create unique index that allows duplicates for null and other specified values

I have a "header.header.message-id" in my document JSON structure for which I created an index, that looks like this in an output from db.archives.getIndexes():

{
"key": {
  "header.header.message-id": 1
},
"name": "header.header.message-id_index",
"v": 2,
"background": false
} 

I need to create an index that allows duplicates for null and other specified values. For example, I want to accept when "header.header.message-id" is empty, as well as if it equals: "#1/1" (which appears a lot in my documents). Other than that, all duplicates should be rejected.

Upvotes: 2

Views: 768

Answers (1)

jjj
jjj

Reputation: 2672

Ok, did not get an answer on this site, but I have eventually figured it out. The index had to be defined in the following way to ensure it's only accepting unique values for key "header.header.message-id", except for null values and those that equal to "#1/1".

  {
    "key": {
      "header.header.message-id": 1
    },
    "name": "header.header.message-id_index",
    "partialFilterExpression": {
      "header.header.message-id": {
        "$exists": true,
        "$gt": "#1/1"
      }
    },
    "unique": true
  }

I've tested it and it works as specified.

Upvotes: 1

Related Questions