How to select attached documents in mongodb?
Suppose I have nested documents with this structure:
{
"_id": "a125",
"Language": null,
"Name": "Some name",
"Related": [{
"_id": "b125",
"Status": 0,
}, {
"_id": "b126",
"Status": 1,
}]
}
is it possible with C # drivers to select the "Linked" model where id is b126 and at the same time get the id of the parent document (a125)?
As I think the result should look like this:
{
"_id": "a125",
"Related": {
"_id": "b126",
"Status": 1,
}
}
source to share
You can use dot notation with the positional$
projection operator to find the matching document and include only the matching element Related
.
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();
source to share
You should use dot notation for your purpose. Your request will look like this:
{"Related._id": "b126"}
This will bring you all documents with all fields, including the parent _id
, where there is a document element in the array Related
that has a field _id
with a value"b126"
source to share