Projection in Where Clause Query of a Embedded document in MongoDB Collection using C#

前端 未结 3 714
悲&欢浪女
悲&欢浪女 2021-01-23 10:00

Filter the Collection in DB instead of Memory

I\'m having a Model Class, Save it in a MongoDB Collection then Query the same as per my expec

3条回答
  •  执念已碎
    2021-01-23 10:21

    I think this would solve the problem that you have:

    var collection = _database.GetCollection("employee"); // (1)
    
    var filterBuilder = Builders.Filter;
    var filter = filterBuilder.Eq("IsLive", true) & filterBuilder.Eq("EmpMobile.IsLive", true); // (2)
    
    var results = await collection.FindAsync(filter).ToListAsync(); // (3)
    

    (1): You will need to change the collection name with the collection name that has the data you want to query. Also, notice that it requests a TDocument as the generic parameter. It seems that Employee does not inherit from TDocument, but you can do so or you can create another DTO class for this purpose.

    (2): You can combine conditions by using the bit AND operator (&).

    Also, you can query directly against internal values of an array (which you have in your classes as a list). As it turns out, it will return the document if any of the array values satisfies the condition. In your example, this should return the document for EmpIDs 100, but it will contain both of the MobileNumbers in it. You retrieved the document that satisfied the condition, but you retrieved the document in its entirety.

    (3) Finally, rendering the results to a list so you have them in memory. Alternatively, you can walk through the results using cursor.MoveNextAsync(), but this will keep your connection to MongoDB open longer.

    You can find most of the information with examples in the Find or Query Data with C# Driver of the MongoDB docs.

提交回复
热议问题