Lets say I have a nested documents with this stucture:
{
"_id": "a125",
"Language": null,
"Name": "Some name",
"Related": [{
"_id": "b125",
"Status": 0,
}, {
"_id": "b126",
"Status": 1,
}]
}
is it possible using c# drivers to select "Related" model where id is b126 and at the same time to get parent document id (a125)?
As I imagine outcome should look like this:
{
"_id": "a125",
"Related": {
"_id": "b126",
"Status": 1,
}
}
You can query for multiple documents in a collection with collection.find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.
MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document.
Use the $elemMatch operator to query embedded documents. Use conditional operators to query embedded documents. Use Visual Query Builder to query embedded documents.
Use $match With $eq to Find Matching Documents in an Array in MongoDB. Use $match With $all to Find Matching Documents in an Array in MongoDB.
You can use dot notation with the positional $
projection operator to find the matching document and only include the matching Related
element.
In the shell:
db.test.findOne({'Related._id': 'b125'}, {'Related.$': 1})
To do this in C#:
var filter = Builders<BsonDocument>.Filter.Eq("Related._id", "b125");
var projection = Builders<BsonDocument>.Projection.Include("Related.$");
var result = await collection.Find(filter).Project(projection).FirstAsync();
You should use dot notation for your purpose. Your query will look like this:
{"Related._id": "b126"}
This will bring you all the documents, with all the fields including your parent _id
, where there is a document element in the Related
array, which has a field _id
with value "b126"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With