[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 Created: 30/Mar/17  Updated: 29/Jul/22

Status: Backlog
Project: C# Driver
Component/s: API
Affects Version/s: 2.4.3
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Mardoxx Assignee: Unassigned
Resolution: Unresolved Votes: 8
Labels: size-small
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Net452


Issue Links:
Depends
is depended on by CSHARP-1309 IndexKeysDefinitionBuilder should sup... Backlog

 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)));
        }
    }
}



 Comments   
Comment by Emanuel M [ 05/Oct/17 ]

Hello, I'm also interested in this feature. Is there anybody that can give me an update on it? Thank you.

Comment by Brian Buvinghausen [ 22/Aug/17 ]

Adding +1 for no magic strings...

Comment by Robert Stam [ 06/Apr/17 ]

There is currently no way to use the type safe index key builders to create an index on a nested field of an array of documents.

The workaround in the current release is to use a string to identify the nested field.

We will look into how this might be supported in a future release.

Generated at Wed Feb 07 21:41:11 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.