如何在 MongoDB 数组的 objects 中查找包含字符串的 collection 记录?

How to find collection records contains string in objects of array in MongoDB?

我 MongoDB collection 有多个记录。每条记录都有一个数组,其中包含 objects 和多个字段。

我有 collection 如下所示:

[{
    "name" : "Karthik Thurairaja"
    "universities" : [ 
        {
            "name" : "Anna University",
            "city" : "Chennai"
        },
        {
            "name" : "Punjab University",
            "city" : "Chandigarh"
        },
        {
            "name" : "University of Delhi",
            "city" : "New Delhi"
        }
    ],
},
{
    "name" : "Sathish Kumar"
    "universities" : [ 
        {
            "name" : "Anna University",
            "city" : "Chennai"
        },
        {
            "name" : "University of Hyderabad",
            "city" : "Hyderabad"
        },
        {
            "name" : "University of Delhi",
            "city" : "New Delhi"
        }
    ],
}]

我需要查找大学城市等于金奈的所有记录。

我试过如下查询:

Collection.find({ universities.city : "Chennai" }).exec(...);

您可以使用 $elemMatch 查询来实现此目的。

Collection.find({ universities: { $elemMatch: { city: "Chennai" } } }).exec(...);