Advice please - A collection with a unique list of services

Hello, I was reading an official article on the MongoDB website where the following collection was used as a learning example:

    {
        "_id": "nraboy",
        "cards": [
            {
                "name": "Charizard",
                "set": "Base",
                "variant": "1st Edition",
                "value": 500000
            },
            {
                "name": "Pikachu",
                "set": "Base",
                "variant": "Red Cheeks",
                "value": 350
            }
        ]
    },

However, the article has left me with 1 question unanswered: is there a way to prevent inserting/ updating duplicated? For example, is there any way to not allow inserting another object that has a name “Pikachu” again?

Thank you

Enjoy the fine writing

Hello, thanks for the reply, however I could not find an answer to my question under your link. In fact, it appears I need exactly the opposite of what you posted.

Rephrased:

How does one disallow multiple Pikachus being created. Example:

Suppose Pikachu does not exist yet in the collection, how do I make it unique so that this is disallowed:

        "cards": [
            {
                "name": "Pikachu",
                "set": "Base",
                "variant": "Red Cheeks",
                "value": 350
            },
         {
                "name": "Pikachu",
                "set": "Base",
                "variant": "Yellow",
                "value": 740
            },
         {
                "name": "Pikachu",
                "set": "Base",
                "variant": "Red Cheeks",
                "value": 600
            },
         {
                "name": "Pikachu",
                "set": "Upgraded",
                "variant": "Red Cheeks",
                "value": 350
            },
        ]

Furthermore, another Pikachu should be perfectly allowed in another document. In other words, the restraint encompasses the document’s array only.

The title of the post is A collection with a unique … so I assumed you wanted to ensure that no documents have the same value. This can be done with unique index which was the purpose of the link I shared.

Making sure that an array cannot have duplicate value is a completely different requirement.

This you can do by adding the following in your query part for your $push

"cards.name" : { "$ne" : "Pikachu" }

This $push will be only done if none element of the array cards have name:Pikachu.

1 Like