Consider the following object structure stored as documents:
public class Foo
{
public string Id { get; set; }
public List<FooBar> Bars { get; set; }
// ...
}
public class FooBar
{
public string uid { get; set; }
// ...
}
I have an array of strings :
var ArrayOfUid = ["STK-00112","STK-00117","STK-00113","STK-00114"]
I want to get all the products where FooBar.uid
in ArrayOfUid
So in the end I get the list of products like this without duplicates
on MongoDb Side query :
db.collection.find({
"foobar.uid": {
$in: [
"STK-00113",
"STK-00117",
"STK-00113",
"STK-00114"
]
}
})
Is there a way to do it with the array of strings?
At the moment I can achieve it with only one given string like this :
var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch(
foo => foo.Bars,
foobar => foobar.uid == "STK-00113"));
This will return the object that has the
foobar.uid
= "STK-00113"
Is there a way to go through the array of strings and return the list of all objects?
Edit
public List<Produit> Get() =>
_produits.Find(produit => true).ToList();
will return this list of products :
[
{
"_id": {
"$oid": "6152da109e0ced07f16a3fom"
},
"uid": "20210915-67102",
"type": "N1",
"foobar": [
{
"uid": "STK-00117",
"nom": "JOHN DOE T1"
},
{
"uid": "STK-00114",
"nom": "JOHN DOE T5"
}
]
},
{
"_id": {
"$oid": "6152da109e0ced07f16a3fxs"
},
"uid": "20210915-67108",
"type": "N5",
"foobar": [
{
"uid": "STK-00117",
"nom": "JOHN DOE T3"
},
]
},
{
"_id": {
"$oid": "6152da109e5ced07f16a3fdc"
},
"uid": "20210915-67108",
"type": "N12",
"foobar": [
{
"uid": "STK-00115",
"nom": "JOHN DOE T4"
},
{
"uid": "STK-00117",
"nom": "JOHN DOE T10"
},
{
"uid": "STK-00113",
"nom": "JOHN DOE T18"
},
]
},
{
"_id": {
"$oid": "6152da609e0ced07f16a3fdc"
},
"uid": "20210915-67108",
"type": "N17",
"foobar": [
{
"uid": "STK-00113",
"nom": "JOHN DOE T15"
},
{
"uid": "STK-00112",
"nom": "JOHN DOE T16"
},
{
"uid": "STK-00111",
"nom": "JOHN DOE T17"
},
]
},
{
"_id": {
"$oid": "6152da109e0ced07f16a3f5e"
},
"uid": "20210915-67108",
"type": "N16",
"foobar": [
{
"uid": "STK-00999",
"nom": "JOHN DOE T99"
},
]
}]
And this is my service function :
public List<Produit> GetFromSitesAsync(List<string> productSites)
{
// WORKING BUT EMPTY
FilterDefinition<Produit> filter = new BsonDocument(
"foobar.uid",
new BsonDocument(
"$in",
BsonArray.Create(productSites)
)
);
return _produits.Find(filter).ToList();
}
NB :
productSites = ["STK-00112","STK-00117","STK-00113","STK-00114"]
2
Answers
You can set
filter
withBsonDocument
object as below:OR
Write MongoDB query and deserialize to
BsonDocument
.FYI, you can use MongoDB Compass to export Query to C# Language.
the generated query will be:
UPDATE:
I used the shell to insert the data you mentioned in the original question and it works: