我们可以在MongoDB中搜索对象数组吗?
是的,要搜索对象数组,请在MongoDB中使用$unwindaggregate()。要匹配,请使用$match。让我们创建一个包含文档的集合-
> db.demo623.insertOne(
... {
... _id:1,
... details:[
... {
... Name:"Chris"
... },
... {
... DueDate:new ISODate("2020-01-10")
... },
... {
... CountryName:"US"
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 1 }在find()方法的帮助下显示集合中的所有文档-
> db.demo623.find().pretty();
这将产生以下输出-
{
"_id" : 1,
"details" : [
{
"Name" : "Chris"
},
{
"DueDate" : ISODate("2020-01-10T00:00:00Z")
},
{
"CountryName" : "US"
}
]
}以下是在MongoDB中搜索对象数组的查询-
> db.demo623.aggregate({$unwind: "$details"},
... {$match: {"details.Name":"Chris"}},
... {$project: {"details.Name": 1}})这将产生以下输出-
{ "_id" : 1, "details" : { "Name" : "Chris" } }