Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
  }
}
like image 495
nonSkulas Avatar asked May 18 '15 09:05

nonSkulas


People also ask

How do I search multiple documents in MongoDB?

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.

What is nested document in MongoDB?

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.

What is the preferred method of querying embedded documents in MongoDB?

Use the $elemMatch operator to query embedded documents. Use conditional operators to query embedded documents. Use Visual Query Builder to query embedded documents.

How do you find documents with a matching item in an embedded array?

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.


2 Answers

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();
like image 158
JohnnyHK Avatar answered Oct 18 '22 04:10

JohnnyHK


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"

like image 34
bagrat Avatar answered Oct 18 '22 05:10

bagrat