How to find documents by field taking into account different "schema_version"?


I want to follow schema versioning pattern in my MongoDB schema. Let’s say I have a collection users which represents my users in the app. This collection contains multiple documents with different versions (e.g. schema_version: 1, schema_version: 2 etc.). The different versions of the document have different fields. Take a look at the example below

users = [
    _id: ObjectId("1"),
    full_name: "Jhon Doe",
    _id: ObjectId("2"),
    first_name: "Jane",
    last_name: "Doe",
    schema_version: 2

Let’s say I need to find a user by a name.

Without different schemas I would created a single index on field fullName and use query like

db.collection('users').find({ fullName: "Jane Doe" })

But, how I can achieve the same result considering multiple schemas in the collection?

Does it mean that my query should consider both (or any) existing versions of the document in the collection, like

  $or: [ 
     { full_name: "Jane Doe" }, 
     { first_name: "Jane", last_name: "Doe" } 

If yes, does it mean that I need to create two indexes (each per schema type) to make query performant?


Hi @Roman_Mahotskyi

Yes, it does mean so. A simple index for v1 and a compound index for v2. I think they should be sparse indexes, but am no expert.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.