Selecting an embedded object using LINQ (from MongoDB)
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/point开发者_JAVA技巧ers.
-Mike
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
Use map/reduce to retrieve the embedded document.
精彩评论