nonSkulas
nonSkulas

Reputation: 71

how to select nested documents in mongodb?

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,
  }
}

Upvotes: 7

Views: 3491

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

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();

Upvotes: 4

bagrat
bagrat

Reputation: 7418

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"

Upvotes: 3

Related Questions