3

I have array in a document like this

 {
    "samples": [
        [
            25,
            "1535530415"
        ],
        [
            "45",
            "1535530415"
        ]
    ]
}

and i try to fetch the value based on second value of each array

my filter query is

 var collection = database.GetCollection<BsonDocument>("History");
        FilterDefinition<BsonDocument> filterDefintion = null ;
        ProjectionDefinition<BsonDocument> project = Builders<BsonDocument>.Projection.Include("samples").Exclude("_id");
        filterDefintion =  Builders<BsonDocument>.Filter.Eq("samples[1]","1535530415");

but it getting an empty array.how to filter the array values in mongo c# driver.

1 Answer 1

2

Your sample document contains an array of arrays. To reference item at index 1 you can take advantage of the fact that in JS an array can be considered as an object where indexes are the properties, so in your case what you're storing can also be interpreted as:

{
    "samples": [
        {
            "0": 25,
            "1": "1535530415"
        },
        {
            "0": 45,
            "1": "1535530415"
        }
    ]
}

knowing that you can use $elemMatch to reference the right element:

db.History.find({ "samples": { $elemMatch: { 1: "1535530415" } } })

or in C# code:

filterDefintion = Builders<BsonDocument>.Filter.ElemMatch<BsonDocument>("samples", new BsonDocument() { { "1", "1535530415" } });
Sign up to request clarification or add additional context in comments.

3 Comments

mickl is it possible to check the key (ex "0" ) is present or not?
@arunthomas sure, you can use $exists operator, like: db.History.find({ "samples": { $elemMatch: { 1: "1535530415" } }, "samples.1": { $exists: true } })
in C# code: Builders<BsonDocument>.Filter.Exists("0");

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.