Littlebobbydroptables
Littlebobbydroptables

Reputation: 3731

MongoDB createIndex in PHP

I am storing my articles view count in MongoDB like this

    $mongoCollection = $this->mongoClient->db->collectionName;

    $mongoCollection->findAndModify(
        [
            'id' => (int)$article_id
        ],
        [
            '$inc' => [
                'count' => 1
            ]
        ],
        null,
        [
            'upsert' => true
        ]
    );

Now i need to add an index, so i am just adding

    $mongoCollection->createIndex(['id' => 1]);

right after

    $mongoCollection = $this->mongoClient->db->collectionName;

but this gives me

Index with name: id_1 already exists with different options

But why? By http://php.net/manual/en/mongocollection.createindex.php and https://docs.mongodb.org/v3.0/tutorial/create-an-index/ it must work?

What am i doing wrong? And is it right to add

    ['unique' => true, 'dropDups' => 1]

in this case?

Upvotes: 0

Views: 974

Answers (1)

Martin
Martin

Reputation: 5332

Well the error message says it all: Index with name: id_1 already exists with different options

You all ready have an index with that name. You only need to create an index once - not every time you connect to the database.

Upvotes: 2

Related Questions