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

    XMLWordPrintable

    Details

    • Type: New Feature
    • Status: Open
    • Priority: Major - P3
    • Resolution: Unresolved
    • Affects Version/s: 2.4.3
    • Fix Version/s: None
    • Component/s: API
    • Environment:
      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

            • Votes:
              3 Vote for this issue
              Watchers:
              6 Start watching this issue

              Dates

              • Created:
                Updated: