6

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?

3 Answers 3

6

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();
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.