mongodb 如何包含Mongo对象中的嵌套字段?

mcvgt66p  于 2023-01-16  发布在  Go
关注(0)|答案(1)|浏览(150)

实体

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace HelloWorldApi.Entities;

public class Deck
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = ObjectId.GenerateNewId().ToString();

    public string Name { get; set; } = "";

    public List<string> Cards { get; set; } = new();
}

public class Credentials
{
    public string Username { get; set; } = "";
    public string Password { get; set; } = "";
}

[BsonIgnoreExtraElements]    
public class Account {
    public string Status = "";
    public string Type = "";
    public Credentials Credentials = new();
}

[BsonIgnoreExtraElements]
public class Player
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = "";
    
    public Account Account = new ();

    public List<string> Roles { get; set; } = new ();

    public List<Deck> Decks { get; set; } = new ();

    public List<string> Cards { get; set; } = new ();
}

该服务:

public List<Player> GetUsers()
{
  return _players.FindSync<Player>(FilterDefinition<Player>.Empty).ToList();
}

具体来说,我希望包括帐户、凭据、用户名,但不包括密码。

bmp9r5qi

bmp9r5qi1#

你需要蒙戈projection
该文档添加了一个示例:

var filter = Builders<BsonDocument>.Filter.Eq("status", "A");
var projection = Builders<BsonDocument>.Projection.Include("item").Include("status").Exclude("_id");
var result = collection.Find<BsonDocument>(filter).Project(projection).ToList();

所以你可以这样做

var projection = Builders<Player>.Projection
    .Include(x => x.Account.Credentials.Username)
    .Exclude(x => x.Account.Credentials.Password);

return _players.FindSync<Player>(FilterDefinition<Player>.Empty)
    .Project(projection)
    .ToList();

相关问题