0

I feel like this must be simple to do but can't get it done - any help would be greatly appreciated. I am relatively new to LINQ and MongoDB.

I have the following two entities:

class ParentObject
{
    GUID ParentId {get;set;}
    IList<ChildObject> ChildObjects {get;set;}
    ...other properties

    ParentObject()
    {
        childObjects = new List<ChildObject>();
    }
}

class ChildObject
{
    GUID ChildId {get;set;}
    ...other properties
}

That I'm persisting to a MongoDB instance (as one document, with the subdocuments embedded). What I need to do is retrieve only one of the ChildObject sub-documents stored within the ParentObject document using the ParentId and ChildId. I have the following method/method call that almost does what I want but I'm only able to return an IList or one specific ChildObject based on the index (o, 1, etc):

// I know this won't work    

var parentId = (Some GUID);
var childId = (Some GUID);

var result = 
    SingleWithSelect<ParentObject, ChildObject>
    (
        x => x.Id == parentId && x.ChildObjects.ChildId == ChildId, 
        y => y.ChildObject  
    );


public TResult SingleWithSelect<T, TResult>(
    System.Linq.Expressions.Expression<Func<T, bool>> whereExpression,
    System.Linq.Expressions.Expression<Func<T, TResult>> selectExpression)
    where T : class, new()
        {
            TResult retval = default(TResult);
            using (var db = Mongo.Create(ConnectionString()))
            {
                retval = db.GetCollection<T>().AsQueryable()
                            .Where(whereExpression)
                            .Select(selectExpression)
                            .SingleOrDefault();
            }
            return retval;

        }

Many thanks in advance for any help/pointers.

-Mike

2
  • 1
    Just two steps: 1. Load parent by parentId. 2. Get child by child id from parent: parent.ChildCollection.Single(x=> x.Id == childId); Commented Mar 2, 2011 at 23:46
  • That works, it'd be nicer to do it on the server side but since it's not supported this'll do - thank you. Commented Mar 3, 2011 at 15:50

2 Answers 2

1

This is not currently supported in Mongodb itself. On a match, the entire document is returned and not just the matched subdocument. I am not sure if norm provides support for this and filters on the driver side. The open JIRA item for this feature request on mongodb is http://jira.mongodb.org/browse/SERVER-828

Sign up to request clarification or add additional context in comments.

Comments

0

Use map/reduce to retrieve the embedded document.

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.