Pergunta

i trying to create an unique multikey index based on two fields :

My document :

> db.users.find().pretty()
{
        "_class" : "bean.User",
        "_id" : ObjectId("52f3945e2f9d426e9dcb1ac8"),
        "commandes" : [
                {
                        "idCommande" : 1,
                        "nom" : "toto",
                        "prenom" : "TATA",
                        "adresse" : "",
                        "ville" : "Brest",
                        "codePostal" : "29200",
                        "montantTotal" : 0,
                        "voyagesSouscrits" : [
                                {
                                        "idVoyage" : "123",
                                        "duree" : 10,
                                        "nbPersonnes" : 0,
                                        "villeDepart" : "Nantes",
                                        "prixVoyage" : 100000
                                }
                        ]
                }
        ],
        "mail" : "toto@toto.fr",
        "password" : "1234"
}

I already ensure an unique index on my mail. And now i want to creat an unique constrain for each "idCommande", then it would not be possible to create an "commande" with same "idCommande" in my user's "commandes".

i tried an

db.users.ensureIndex({_id : 1, idCommande : 1 },{unique :true});

and also :

db.users.ensureIndex({_id : 1, idCommande : 1 },{unique :true, multikey : true});

but i stil can insert same "idCommande".

I know addToSet exists, but i don't want a constrain on my global document

Have you got any idea ?

Thanks in advance

Foi útil?

Solução

I think

db.users.ensureIndex({_id: 1, "commandes.idCommande" : 1 },{unique :true})

should be enough

Outras dicas

No the answer should be

db.users.ensureIndex({"commandes.idCommande" : 1 },{unique :true});

This will prevent duplicate entries for 'idCommande'.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top