Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query nested documents with C# MongoDB

Tags:

c#

mongodb

nosql

I have a document called Record which contains an Athlete as a nested document. The structure looks like this in JSON:

{
  "Id": "000000000000000000000000",
  "Description": "sample string 1",
  "Athlete": {
    "Id": "123456789101112131415161",
    "Name": "sample string 2",
    "Username": "sample string 3",
    ...
  },
  ...
}

How do you query this structure to retrieve the Record object based on the Athlete.Id? I.E. If i have the ID of the athlete and I want to retrieve their record, how would you do this?

like image 916
user1636130 Avatar asked Dec 11 '14 14:12

user1636130


3 Answers

Way 1 : Using raw BsonDocument: (it will return list of BsonDocument)

var queryString = Query.EQ("Athlete.Id", "123456789101112131415161");
var resultBsons = collection.Find(queryString).ToList();

Way 2 : Another way is using Typed version of mongodb c# driver:

define 2 classes:

public class Athlete
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Username { get; set; }
}

public class Record
{
    public string Id { get; set; }
    public string Description { get; set; }
    public Athlete Athlete { get; set; }
}

then do your query

var url = new MongoUrl("mongodb://localhost");
var client = new MongoClient(url);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<Record>("records");

var query = Query<Record>.EQ(i => i.Athlete.Id, "123456789101112131415161");
var result = collection.Find(query).ToList();
like image 197
2 revs, 2 users 67% Avatar answered Oct 16 '22 14:10

2 revs, 2 users 67%


Beside what was already said, this blog could help you with more complex situations. Basically it could look like:

records.Find(
  Query.ElemMatch("Athlete",
  Query.EQ("Id", athleteId)
));
like image 3
thmshd Avatar answered Oct 16 '22 14:10

thmshd


You can query by a sub-document field using exactly the format you provided: Athlete.Id.

db.collection_name.findOne({"Athlete.Id": "123456789101112131415161"})

EDIT: To do this in C#, you can do something like this assuming you defined the structure of a Record document in a class called Record:

IMongoQuery query = Query.EQ("Athlete.Id", "123456789101112131415161");
Record result = collection_name.FindOne(query); 

Or if multiple documents may be returned with that matching Id:

IMongoQuery query = Query.EQ("Athlete.Id", "123456789101112131415161");
MongoCursor<Record> resultCursor = collection_name.FindOne(query); 
like image 1
CynicalProgrammer Avatar answered Oct 16 '22 13:10

CynicalProgrammer