[CSHARP-669] Retrieve Many-to-Many Object collection vai ObjectId Array Created: 24/Jan/13  Updated: 20/Mar/14  Resolved: 13/Feb/13

Status: Closed
Project: C# Driver
Component/s: None
Affects Version/s: 1.7
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: ErhWenKuo Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

In order to do the many-to-many between tmpCategory & tmpProduct, I use a ObjectId list to store the which category that a product related to. When I get the "tmpProduct" object back from C# driver and would like to use "tmpProduct.Category_Ids" to retrieve the tmpCategory collection back utilize below method:

var categories = mongoCollection_Category.FindAs<tmpCategory>(Query.In("_id",product.Category_Ids));

=> C# complains that product.Category_Ids is not IEnumerable<BsonValue>??
=> However, the LINQ statement would work like below:

var categories2 = (from obj in mongoCollection_Category.AsQueryable<tmpCategory>()
where obj.Id.In(product.Category_Ids)
select obj).ToList<tmpCategory>();

public class tmpCategory
{
public ObjectId Id

{ get; private set; }
public string Title { get; set; }
}

public class tmpProduct
{
private IList<ObjectId> _category_ids = new List<ObjectId>();

public ObjectId Id { get; private set; }

public string Name

{ get; set; }

public IList<ObjectId> Category_Ids
{
get

{ return _category_ids; }

set

{ _category_ids = value; }

}
}

Would it be easier to have C# driver to add below methods?

1.Query.In("_id", IEnumerable<ObjectId>)
2.MongoCollection.FindAllByIdsAs(IEnumerable<ObjectId>)



 Comments   
Comment by Craig Wilson [ 24/Jan/13 ]

You can do this in 1 of 3 ways. As you have statement that Linq works, any reason not to use it?

2) Your version casting the ObjectId into a BsonValue.

var categoryIds = product.Category_Ids.Select(x => (BsonValue)x);
var categories = mongoCollection_Category.FindAs<tmpCategory>(Query.In("_id", categoryIds));

3) Using tje Typed Query Builder. Query<T>.In

var categories = mongoCollection_Category.FindAs<tmpCategory>(Query<tmpCategory>.In(x => x.Id, product.Category_Ids));

Generated at Wed Feb 07 21:37:30 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.