简体   繁体   中英

MongoDB C# search array of objects for intersection with a list on a single field

I'm trying to search a embedded array of documents in my MongoDB documents for a match in a list of ObjectIds I have in a C# list.

For example If I have a class object in mongodb looking like this

{
 "_id": $oid,
 "Name":"Politics 101",
 Students: [{ "_id": 'theirid', "Name": "Ghengis Khan", "StudentId": 12345 }, ... ]
}
  

How can I query that list towards all classes containing a student with a student ID I have in a list with C#?

If the embedded list was just an array of studentIds I think I could just do something like this

List<int> studentIds = new List<int>() { 12345,123213,434233,234232,42312,776433 }
FilterDefinition<Class> filter = Builders<Class>.Filter.AnyIn(c => c.Students, studentIds);
var desiredClasses = database.Classes.Class.Find(filter).ToListAsync() 

But what do I do when I need to match a field in an array of embedded documents?

Solution 1: Work with .ElemMatch()

MongoDB query

db.collection.find({
  "Students": {
    $elemMatch: {
      "StudentId": {
        $in: [
          12345,
          123213,
          434233,
          234232,
          42312,
          776433
        ]
      }
    }
  }
})

Demo Solution 1 @ Mongo Playground

MongoDB .NET Driver syntax

FilterDefinition<Class> filter = Builders<Class>.Filter.ElemMatch(c => c.Students,
    Builders<Student>.Filter.In(s => s.StudentId, studentIds));

Demo

在此处输入图像描述


Solution 2: Work with .In() and dot notation

MongoDB query

db.collection.find({
  "Students.StudentId": {
    $in: [
      12345,
      123213,
      434233,
      234232,
      42312,
      776433
    ]
  }
})

Demo Solution 2 @ Mongo Playground

MongoDB .NET Driver syntax

FilterDefinition<Class> filter = Builders<Class>.Filter
    .In($"{nameof(Class.Students)}.{nameof(Student.StudentId)}", studentIds);

Demo

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM