Encontré que la forma de verificar es el valor contenido en una matriz simple:
var filter = Builders<Post>.Filter.AnyEq(x => x.Tags, "mongodb");
Pero, ¿cómo encontrar un elemento complejo con muchos campos por un campo concreto? Encontré la manera de escribirlo a través del enfoque de notación de puntos con el generador BsonDocument
, pero ¿cómo puedo hacerlo con notaciones lambda escritas?
actualización
creo que es una especie de
builderInst.AnyIn(p => p.ComplexCollection.Select(ml => ml.Id), mlIds)
pero no se puede comprobar en este momento, ¿alguien podría ayudar?
Hay ElemMatch
var filter = Builders<Post>.Filter.ElemMatch(x => x.Tags, x => x.Name == "test"); var res = await collection.Find(filter).ToListAsync()
Aquí hay un ejemplo que devuelve un solo elemento complejo de una matriz (usando MongoDB.Driver v2.5.0):
Modelo de datos simples
public class Zoo { public List<Animal> Animals { get; set; } } public class Animal { public string Name { get; set; } }
Opción 1 (Agregación)
public Animal FindAnimalInZoo(string animalName) { var zooWithAnimalFilter = Builders<Zoo>.Filter .ElemMatch(z => z.Animals, a => a.Name == animalName); return _db.GetCollection<Zoo>("zoos").Aggregate() .Match(zooWithAnimalFilter) .Project<Animal>( Builders<Zoo>.Projection.Expression<Animal>(z => z.Animals.FirstOrDefault(a => a.Name == animalName))) .FirstOrDefault(); // or .ToList() to return multiple }
Opción 2 (Filtro y Linq) Esto fue aproximadamente 5 veces más lento para mí
public Animal FindAnimalInZoo(string animalName) { // Same as above var zooWithAnimalFilter = Builders<Zoo>.Filter .ElemMatch(z => z.Animals, a => a.Name == animalName); var zooWithAnimal = _db.GetCollection<Zoo>("zoos") .Find(zooWithAnimalFilter) .FirstOrDefault(); return zooWithAnimal.Animals.FirstOrDefault(a => a.Name == animalName); }
Necesita el operador $elemMatch
. Podría usar Builders<T>.Filter.ElemMatch
o una expresión Any
:
Find(x => x.Tags.Any(t => t.Name == "test")).ToListAsync()
http://mongodb.github.io/mongo-csharp-driver/2.0/reference/driver/expressions/#elemmatch