Reputation: 1150
I have an application that was using native mongoDb, we're now pointing it to an Azure Cosmos DB instance, but we're now not getting results when querying arrays.
For example, we have the following customer:
{
"email" : "[email protected]",
"data" : {
"customerGuid" : "a30b5d75ca6241dcbd0260b2516a2165",
"addresses" : [
{
"firstName" : "firstname",
"lastName" : "lastname",
"postalCode" : "SY1 3VE",
}
]
}
}
And we're using the MongoDB.Driver (via AsQueryable and linq) to find all customers matching on an item in the addresses array
i.e.
var col = db.GetCollection<Customer>("Customer");
var custQuery = col.AsQueryable()
.Where(c => c.Data.Addresses.Any(a => a.PostalCode == "SY1 3VE"));
But, I am not getting any matches. Digging in further, it seems to be generating a Mongo query that looks like:
{aggregate([{ "$match" : { "data.addresses.postalCode" : "SY1 3VE" } }])}
Which doesn't work for me when I try manually against the database either.
Am I doing something wrong? Or is the Cosmos Mongo Db implementation not fully compatible with the MongoDB.Driver yet?
Upvotes: 0
Views: 871
Reputation: 24529
Am I doing something wrong? Or is the Cosmos Mongo Db implementation not fully compatible with the MongoDB.Driver yet?
As you mentioned the Cosmos Mongo Db may have not implemented whole commands as native MongoDB. I tried the code you mentioned also get
there is no record returned
But we could use filter to do that, I tested with following code. It works correctly on my side.
var collection = db.GetCollection<BsonDocument>("BsonDocument");
var test = collection.Find(Builders <BsonDocument>.Filter.ElemMatch<BsonDocument>("data.addresses",
"{\"postalCode\":\"SY1 3VE\"}")).ToList();
Another option:
Based on my experience, it is not recommended, as it will query all of the documents to client.
var col = db.GetCollection<Customer>("Customer");
var custQuery = collection.AsQueryable().ToList().Where(c => c.Data.Addresses.Any(a => a.PostalCode == "SY1 3VE"));
Upvotes: 1