0

Let's say I have an abstract class Animal, and subclasses Dog and Cat.

My MongoDB table stores all animals, and uses a the _t type discriminator field in documents.

What I want to do is create a full-text index on 2 properties, one that exists only in Dog documents, and one that exists only in Cat documents. The JSON is straightfoward enough:

{ 
    "dog_only_field" : "text", 
    "cat_only_field" : "text"
}

But I'd like to do this with the official C# driver. I tried this:

var builder = Builders<Animal>.IndexKeys;
var keys = builder.Text(x => ((Dog)x).MyText).Text(x => ((Cat)x).MyText);
col.Indexes.CreateOne(keys);

But got Unable to determine the serialization information for x => Convert(x).Message.

3
  • How does your Cat, Dog and Animal classes look like? Please post bare minimum testable code. Commented Mar 31, 2016 at 14:01
  • @Saleem TBH, I'm not sure it adds anything useful to understanding the question, but let's say that Animal only has a Guid Id property, Dog has a string property DogText and Cat has a string property CatText. Commented Mar 31, 2016 at 14:12
  • It's not about understanding but testing also. Problem may be crystal clear to you but think about others who have no clue of your thought process. Commented Mar 31, 2016 at 14:15

1 Answer 1

1

I got this working by using field definitions that specify the JSON property name as a string:

var dogFieldDef = new StringFieldDefinition<Animal>("dog_only_field");
var catFieldDef = new StringFieldDefinition<Animal>("cat_only_field");

var builder = Builders<Animal>.IndexKeys;

var key = builder
    .Text(dogFieldDef)
    .Text(catFieldDef);

col.Indexes.CreateOne(key);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.