如何仅显示在MongoDB中的数组中找到的元素?
要仅显示在数组中找到的元素,请使用aggregate()。让我们创建一个包含文档的集合-
> db.demo204.insertOne( ... { ... "_id" : 101, ... "Name" : "Chris", ... "Age" : 23, ... "details" : [ ... { ... "id" : "1001", ... "empId" : "John_1001", ... "salary" : "50000", ... "Technology" : "Java" ... }, ... { ... "id" : "1002", ... "empId" : "John_1002" ... }, ... { ... "id" : "1003", ... "empId" : "John_10003", ... "salary" : "60000", ... "Technology" : "MongoDB" ... } ... ] ... } ...); { "acknowledged" : true, "insertedId" : 101 }
在find()方法的帮助下显示集合中的所有文档-
> db.demo204.find();
这将产生以下输出-
{ "_id" : 101, "Name" : "Chris", "Age" : 23, "details" : [ { "id" : "1001", "empId" : "John_1001", "salary" : "50000", "Technology" : "Java" }, { "id" : "1002", "empId" : "John_1002" }, { "id" : "1003", "empId" : "John_10003", "salary" : "60000", "Technology" : "MongoDB" } ] }
以下是仅显示在MongoDB中的数组中找到的元素的查询-
> db.demo204.aggregate( ... [ ... { "$match": { "details.id": "1001" }}, ... { "$unwind": "$details" }, ... { "$match": { "details.id":"1001" }}, ... { "$project": { "Technology": "$details.Technology", "_id":0 }} ... ] ...)
这将产生以下输出-
{ "Technology" : "Java" }