1

How to include a new item in the array of items in an object in MongoDB with C#?

I tried to use the AddToSet method, but I did not succeed.

I have the following code structure:

1 - Parent object (Revenda):

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;

namespace api.mstiDFE.Entidade.api.mstiDFE
{
    public class Revenda : Notificavel, IEntidade
    {

        public Revenda(string Id, long Codigo, string CPF, string CNPJ, List<RevendaCliente> Clientes)
        {
            this.Id = Id;
            this.Codigo = Codigo;
            this.CPF = CPF;
            this.CNPJ = CNPJ;
            this.Clientes = Clientes;
        }

        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; private set; }

        [BsonElement("Codigo")]
        public long Codigo { get; private set; }

        [BsonElement("Nome")]
        public string Nome { get; private set; }

        [BsonElement("CPF")]
        public string CPF { get; private set; }

        [BsonElement("CNPJ")]
        public string CNPJ { get; private set; }

        [BsonElement("Clientes")]
        public ICollection<RevendaCliente> Clientes { get; private set; }
    }
}

2 - Child object (RevendaCliente):

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System.Collections.Generic;

namespace api.mstiDFE.Entidade.api.mstiDFE
{
    public class RevendaCliente : Notificavel, IEntidade
    {

        public RevendaCliente(string Codigo, string Nome, string CPF, string CNPJ, ICollection<RevendaClienteToken> Tokens)
        {
            this.Codigo = Codigo;
            this.Nome = Nome;
            this.CPF = CPF;
            this.CNPJ = CNPJ;
            this.Tokens = Tokens;
        }

        [BsonElement("Codigo")]
        public string Codigo { get; private set; }

        [BsonElement("Nome")]
        public string Nome { get; private set; }

        [BsonElement("CPF")]
        public string CPF { get; private set; }

        [BsonElement("CNPJ")]
        public string CNPJ { get; private set; }

        [BsonElement("Tokens")]
        public ICollection<RevendaClienteToken> Tokens { get; private set; }
    }
}

3 - Code used to insert a complete parent object:

public Revenda Add(Revenda revenda)
{
    Database.GetCollection<Revenda>("Revendas").InsertOne(revenda);
    return revenda;
}

4 - Code used to recover a specific reseller:

public Revenda FindById(string id)
{
    return CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();
}

Everything works fine.

Here's what I'd like to do.

However, how can I only include a new child object (RevendaCliente) in a parent object (Revenda) already registered in MongoDB?

I am using the following environment: -Microsoft.AspNetCore.App (2.1.1) -MongoDB.Driver (2.8.0)

9
  • you mean adding child object to a MongoDB document? maybe fetch the parent object (Revenda) and add new child object and update it Commented Apr 26, 2019 at 14:43
  • Yes, exactly. This is what I can not do. Bring the in-memory reference for an object stored in MongoDB to the C # context and include a new complex object in one of its properties, in the case "Clientes" This is the code I currently use to retrieve a complete "Revenda " object: public Resend FindById (string id) { return CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault); } Commented Apr 26, 2019 at 14:47
  • can you add this code to the question? Commented Apr 26, 2019 at 14:53
  • I edited the question with the code used to retrieve a reseller. Commented Apr 26, 2019 at 14:57
  • have you tried updating the retrieved object var parentObject=CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();parentObject.Clientes.Add(newChildObject);//now update the parent object Commented Apr 26, 2019 at 15:02

2 Answers 2

1

(as I mentioned in my comment) your problem seems pretty simple, as in MongoDB the related objects in hierarchy are part of the same document, so you need to update your object in-memory and update it.

var parentObject=CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();
parentObject.Clientes.Add(newChildObject);
//now update the parent object
Sign up to request clarification or add additional context in comments.

Comments

0

Code that worked for me: (Resolved with the support of Aarif)

public bool AddRevendaCliente(string revendaId, RevendaCliente requestRevendaClient)
{
    try
    {
        var filter = Builders<Revenda>.Filter.Eq(s => s.Id, revendaId);

        // Get a reference to the parent parent "Revenda"
        var parentObject = CollRevendas.Find<Revenda>(filter).FirstOrDefault();
        parentObject.Clientes.Add(requestRevendaClient);

        // Update the parent object "Revenda"
        var result = CollRevendas.ReplaceOneAsync(filter, parentObject);
    }
    catch (Exception ex)
    {
        throw;
    }            
    return true;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.