0

I have this document structure, the property "Name" must be unique across all documents, as shown above:

{ 
    "_id" : ObjectId("56686341d6389c004c689d5d"), 
    "Bosses" : {
        "B1" : {
            "_id" : NumberInt(1), 
            "Name" : "John"
        },
        "B2" : {
            "_id" : NumberInt(1), 
            "Name" : "Mary"
        }
    }
}

{ 
    "_id" : ObjectId("56686341d6389c004c689d6f"), 
    "Bosses" : {
        "B1" : {
            "_id" : NumberInt(1), 
            "Name" : "Mary" // should throw an error
        }
    }
}

It's possible to create a unique index with this structure?

1 Answers1

1

Yes, you have to create a unique index on Bosses.Name. But then, You'll have to change a little bit your schema. Bosses should be an array:

{ 
    "_id" : ObjectId("56686341d6389c004c689d6f"), 
    "Bosses" : [
        {
            "_id" : NumberInt(1), 
            "Name" : "Mary" // should throw an error
        }
    }
}

If you really need the B1, I suggest you add it into Bosses objects: "Code": "B1". But this might not be necessary, as you can access the index in your array by ...find({ "Bosses.0.Name" })

Constantin Guay
  • 1,604
  • 2
  • 15
  • 26
  • I really need to keep the original structure due to https://jira.mongodb.org/browse/SERVER-3326. I know this is not the best solution, but it avoids aways calls to the database twice when updating a boss. – Diego Prates de Andrade Dec 09 '15 at 18:14
  • Could you explain more the problem your your upsert? Maybe the community can help you to build your upsert in a different way. – Constantin Guay Dec 09 '15 at 18:23