MongoDB C # Get all documents from list of identifiers

I have a list of identifiers

List<string> Ids;

and I would like to receive all documents matching these identifiers.

There are solutions on the Internet:

var ids = new int[] {1, 2, 3, 4, 5};
var query = Query.In("name", BsonArray.Create(ids));
var items = collection.Find(query);

but they are all with the old C # driver and c (not so new). 2.2.4 The API driver has changed, and I cannot find how to build this request.

+4
source share
1 answer

see snippet below (done using LINQPad)

void Main()
{
    // To directly connect to a single MongoDB server
    // or use a connection string
    var client = new MongoClient("mongodb://localhost:27017");
    var database = client.GetDatabase("test");


var collectionEmpInfo = database.GetCollection<Employee>("Employee");
Employee EmpInfo = new Employee
{

    EmpID = "103",
    EmpName = "John",
    CreatedAt = DateTime.Now,
    EmpMobile = new List<Mobile>
    {
        new Mobile{ MobNumber = "55566610", IsPreferred = true, MobID = ObjectId.GenerateNewId() },
        new Mobile{ MobNumber = "55566611", IsPreferred = false, MobID = ObjectId.GenerateNewId() },
    }
};
//collectionEmpInfo.InsertOne(EmpInfo);

var filterDef = new FilterDefinitionBuilder<Employee>();
var filter = filterDef.In(x=>x.EmpID , new[]{"101","102"});
filter.Dump();
var empList = collectionEmpInfo.Find(filter).ToList();
empList.Dump();
}
public class Employee
{
   public ObjectId Id  { get; set; }
    public string EmpID { get; set; }
    public string EmpName { get; set; }
    public List<Mobile> EmpMobile { get; set; }
    public DateTime CreatedAt { get; set; }
}

public class Mobile
{
    public ObjectId MobID { get; set; }
    public string MobNumber { get; set; }
    public bool IsPreferred { get; set; }
}

and a screenshot of the results

linquPaDscreenShot

+7
source

All Articles