Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
¿Cómo selecciono un objeto de una lista MongoDB MVC?

Tengo la siguiente estructura de datos:

 [ { "id": "604ab2c4a568b9181987c9eb", "name": "Paul", "eventDate": "2021-03-12T00:16:03.672Z", "created": "2021-03-12T00:16:03.673Z", "images": [ { "id": "604ab2c3a568b9181987c603", "name": "DSC_0", "url": "https://picsum.photos/300/300", "isSelected": true }, ... ] }, { "id": "604ab3889c5ac2289b450e3c", "name": "Paul", "eventDate": "2021-03-12T00:16:03.672Z", "created": "2021-03-12T00:16:03.673Z", "images": [ { "id": "604ab3879c5ac2289b450a54", "name": "DSC_0", "url": "https://picsum.photos/300/300", "isSelected": true }, ... ] }, ... ]

y estoy tratando de obtener la imagen por la identificación del usuario y la identificación de la imagen, pero no puedo por alguna razón

 var filter = Builders<Client>.Filter.Eq("Id", "604ab2c4a568b9181987c9eb"); filter &= Builders<Client>.Filter.ElemMatch(u => u.Images,t => t.Id == "604ab2c3a568b9181987c603"); return _client.Find(filter).FirstOrDefault();

Esto me está devolviendo todo el documento con la identificación "604ab2c4a568b9181987c9eb", pero solo quería recibir la imagen con la identificación "604ab2c3a568b9181987c603"

Aquí los modelos de los objetos:

 public class Client { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("name")] public string Name { get; set; } [BsonElement("eventDate")] [BsonDateTimeOptions] public DateTime EventDate { get; set; } [BsonElement("created")] [BsonDateTimeOptions] public DateTime Created { get; set; } [BsonElement("images")] public List<Image> Images { get; set; } } public class Image { [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string Id { get; set; } [BsonElement("name")] public string Name { get; set; } [BsonElement("url")] [DataType(DataType.ImageUrl)] public string Url { get; set; } [BsonElement("isSelected")] public bool IsSelected { get; set; } }

Entonces, quería saber cómo podría arreglar mi código para que me devuelva solo una imagen, o más de una imagen del usuario que estoy buscando.

Por último, pero no menos importante, quería saber si puedo cambiar el valor isSelected incluso si estoy usando el mismo filtro.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Quería usar la proyección solo para solicitar la imagen específica con la identificación dada. Entonces la consulta se vería como>

 var client = new MongoClient(); var database = client.GetDatabase("test"); var collection = database.GetCollection<Client>("clients"); //collection.InsertOne(new Client //{ // Created = DateTime.Now, // EventDate = DateTime.Now, // Name = "myClient", // Images = new List<Image> // { // new Image // { // Id = ObjectId.GenerateNewId(DateTime.Now).ToString(), // Name = "Image1", // IsSelected = true, // Url = "myUrl1" // }, // new Image // { // Id = ObjectId.GenerateNewId(DateTime.Now).ToString(), // Name = "Image2", // IsSelected = true, // Url = "myUrl2" // } // } //}); var filter = Builders<Client>.Filter.Eq("Id", "605a60a76b25fefcc3b1bc00"); var imageFilter = Builders<Image>.Filter.Eq("Id", "605a60a76b25fefcc3b1bbff"); var projection = (ProjectionDefinition<Client, Client>)Builders<Client>.Projection.ElemMatch("Images", imageFilter); var image = collection.Find(filter).Project(projection).FirstOrDefault() // here you have the specific client with only the right Image in the Images. Other props are default. ?.Images?[0]; // selecting the only Image in the list.

Lo sentimos, pero la parte de actualización no es tan simple. Tomando un enfoque completamente diferente>

 var filter = Builders<Client>.Filter.Eq(x => x.Id, "605a60a76b25fefcc3b1bc00"); var update = Builders<Client>.Update.Set("images.$[f].isSelected", false); var arrayFilters = new[] { new BsonDocumentArrayFilterDefinition<BsonDocument>( new BsonDocument("f._id", BsonObjectId.Create("605a60a76b25fefcc3b1bbff"))) }; collection.UpdateOne(filter, update, new UpdateOptions { ArrayFilters = arrayFilters });

Principalmente tomado de https://kevsoft.net/2020/03/23/updating-arrays-in-mongodb-with-csharp.html

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!