如何使用C#在MongoDB中的对象的项目数组中包含新项目?
我尝试使用AddToSet方法,但没有成功。
我具有以下代码结构:
1-父对象(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-子对象(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-用于插入完整父对象的代码:
public Revenda Add(Revenda revenda)
{
Database.GetCollection<Revenda>("Revendas").InsertOne(revenda);
return revenda;
}
4-用于恢复特定经销商的代码:
public Revenda FindById(string id)
{
return CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();
}
一切正常。
但是,如何仅在已经在MongoDB中注册的父对象(Revenda)中包括一个新的子对象(RevendaCliente)?
我正在使用以下环境: -Microsoft.AspNetCore.App(2.1.1) -MongoDB.Driver(2.8.0)
答案 0 :(得分:1)
(正如我在评论中提到的那样),您的问题似乎非常简单,因为在MongoDB中,层次结构中的相关对象是同一文档的一部分,因此您需要在内存中更新并更新对象。
var parentObject=CollRevendas.Find<Revenda>(revenda => revenda.Id == id).FirstOrDefault();
parentObject.Clientes.Add(newChildObject);
//now update the parent object
答案 1 :(得分:0)
对我有用的代码:(在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;
}