Keto
Keto

Reputation: 11

Create index in sub document

I have a document in mongoDB same like:

{
    "_id":"jery",
    "pets":{
        "rabbit":{
            "name":"momo",
            "age":2
        },
        "dog":{
            "name":"lizy",
            "age":2
        }
    }
}

This document structure is very easy to update/upsert,but difficulty to analysis.The problem is what should i do to create unique index on field "name"

Upvotes: 0

Views: 1150

Answers (2)

Webdev
Webdev

Reputation: 647

Change your document structure as show below:-

{"_id":"jery","pets":[{"type":"rabbit","name":"momo","age":2},{"type":"dog","name":"lizy","age":2}]}

It will be easy to query then.

Upvotes: 2

Webdev
Webdev

Reputation: 647

For this you need to do something like :-

db.collection.createIndex( {
   "pets.rabbit.name": 1,       
   "pets.dog.name": 1
} )

Upvotes: 1

Related Questions