How to get the records in which the array has all null values?

I want to get only records which having all null values in the array. Below is the sample document, and the first document is my expected result.

    /* 1 */
    {
        "_id" : ObjectId("617003b1c1057b4dc08105e1"),
        "Tag" : [ 
            "null", 
            "null", 
            "null"
        ]
    }

    /* 2 */
    {
        "_id" : ObjectId("617003b1c1057b4dc08105e2"),
        "Tag" : [ 
            "null", 
            "test", 
            "null"
        ]
    }
        public class Test
        {
            public ObjectId Id { get; set; }
            public string[] Tag { get; set; }
        }

        var client = new MongoClient();
        var db = client.GetDatabase("db");
        var bsonColl = db.GetCollection<BsonDocument>("coll");
        bsonColl.InsertMany(
            new []
            {
                BsonDocument.Parse(@"{
    ""Tag"" : [
        ""null"",
        ""null"",
        ""null""
    ]
}"),
                BsonDocument.Parse(@"{
    ""Tag"" : [
        ""null"",
        ""null"",
        ""Test""
    ]
}")
            });

        var typedColl = db.GetCollection<Test>("coll");
        var result = typedColl.AsQueryable().Where(c => !c.Tag.Any(t => t != "null")).ToList();

also, it’s better to specify null in the document without quotes, then you will be able to have more good looking filtering: .Where(c => !c.Tag.Any(t => t != null))

2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.