MongoDB筛选器,以检查二进制字段是否为空

时间:2019-03-13 15:29:34

标签: c# database mongodb

我在MongoDB中有一个较长的二进制Blob(实际上是一个存储的PNG,带有微型图像)。我需要一个过滤器,该过滤器将返回所有带有非空blob的子弹。

我尝试过这样的事情:

var f = Builders<Common.Json.Database.Picture>.Filter.Where(pic => pic.ContentMini.Length > 0 && pic.ContentFull.Length > 0);
var p = Builders<Common.Json.Database.Picture>.Projection.Include(x => x.Slug);
var s = Builders<Common.Json.Database.Picture>.Sort.Ascending(x => x.Slug);

return Collections.Pictures.Find(f)
                            .Project<Common.Json.Database.Picture>(p)
                            .Sort(s)
                            .ToList()
                            .Select(x => x.Slug);

但是这将返回空集。如果将Filter更改为Filter.Empty,我将收到收藏中的所有子弹。

集合定义如下:

[System.Serializable]
public class Picture
{
    [BsonId]
    [JsonIgnore]
    [NonSerialized]
    public ObjectId InternalId;

    [BsonElement("slug")]
    [JsonProperty("slug")]
    public string Slug;

    [BsonElement("author")]
    [JsonProperty("author")]
    public Common.Author Author;

    [BsonElement("owner")]
    [BsonRepresentation(BsonType.String)]
    [JsonProperty("owner")]
    public Guid OwningUserOrGroup;

    [BsonElement("keywords")]
    [JsonProperty("keywords")]
    public List<string> Keywords = new List<string>();

    [BsonElement("last_updated")]
    [JsonProperty("last_updated")]
    public DateTime LastUpdated;

    [BsonElement("is_approved")]
    [JsonProperty("is_approved")]
    public bool IsApproved;

    [BsonElement("is_obsolete")]
    [JsonProperty("is_obsolete")]
    public bool IsObsolete;

    [BsonElement("content_mini")]
    [BsonRepresentation(BsonType.Binary)]
    [JsonIgnore]
    public byte[] ContentMini;

    [BsonElement("content_full")]
    [BsonRepresentation(BsonType.Binary)]
    [JsonIgnore]
    public byte[] ContentFull;
}

1 个答案:

答案 0 :(得分:1)

byte数组将以"content_mini" : BinData(0,"")的形式存储在MongoDB中,因此您可以简单地使用$ne在Mongo shell中构建查询

db.pictures.find( {"content_mini": { $ne: new BinData(0,"") } } )

要使用C#构建该查询,您需要Builders泛型和Ne方法。要过滤掉所有空数组和null值,可以使用以下代码:

var filter = Builders<Picture>.Filter.Ne(f => f.ContentMini, new byte[] { });
var filter2 = Builders<Picture>.Filter.Ne(f => f.ContentMini, null);
var result = Col.Find(filter & filter2).ToList();

您不应使用Filter.Empty,因为它实际上代表了空查询,就像Mongo Shell中的db.col.find({})