Uploaded image for project: 'C# Driver'
  1. C# Driver
  2. CSHARP-1955

Add a type safe way to use the IndexKeys builder to create an index on a nested field of an array of documents

    XMLWordPrintableJSON

Details

    • Icon: New Feature New Feature
    • Resolution: Unresolved
    • Icon: Major - P3 Major - P3
    • None
    • 2.4.3
    • API
    • Net452

    Description

      using MongoDB.Bson.Serialization.Attributes;
      using MongoDB.Driver;
      using System.Collections.Generic;
      using System.Linq;
      using Xunit;
       
      namespace IndexTest
      {
          [BsonIgnoreExtraElements]
          public class Foo
          {
              public Foo() { }
       
              public List<Bar> Bars { get; set; }
          }
       
          [BsonIgnoreExtraElements]
          public class Bar
          {
              public Bar() { }
       
              public string Baz { get; set; }
          }
       
          public class TestClass
          {
              [Fact]
              public void Test()
              {
                  var client = new MongoClient("mongodb://localhost:27017");
                  var database = client.GetDatabase("test");
                  var collection = database.GetCollection<Foo>("foos");
       
                  // Invalid
                  // { "Baz" : 1 }
                  collection.Indexes.CreateOne(Builders<Foo>.IndexKeys.Ascending(x => x.Bars.First().Baz));
       
                  //Invalid
                  // { "Bar.0.Baz" : 1 }
                  collection.Indexes.CreateOne(Builders<Foo>.IndexKeys.Ascending(x => x.Bars[0].Baz));
       
                  // Valid but relies on magic string
                  // { "Bar.Baz" : 1 }
                  collection.Indexes.CreateOne("{\"Bar.Baz\" : 1}");
       
                  // Failure
                  // System.InvalidOperationException : Unable to determine the serialization information for x => x.Bars.Select(y => y.Baz).
                  collection.Indexes.CreateOne(Builders<Foo>.IndexKeys.Ascending(x => x.Bars.Select(y => y.Baz)));
              }
          }
      }
      
      

      Attachments

        Activity

          People

            Unassigned Unassigned
            Mardoxx Mardoxx
            Votes:
            8 Vote for this issue
            Watchers:
            12 Start watching this issue

            Dates

              Created:
              Updated: