如何获取 MongoDB 中子文档字段值的唯一列表?
若要获取子文档字段值的唯一列表,可使用点 (.)。语法如下:-
db.yourCollectionName.distinct("yourOuterFieldName.yourInnerFieldName");为了理解这个概念,让我们使用文档创建一个集合。用于使用文档创建集合的查询如下:-
> db.getDistinctListOfSubDocumentFieldDemo.insertOne(
... {
... "StudentId": 101,
... "StudentPersonalDetails": [
... {
... "StudentName": "John",
... "StudentAge":24
... },
... {
... "StudentName": "Carol",
... "StudentAge":21
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90a9abb74d7cfe6392d7d8")
}
> db.getDistinctListOfSubDocumentFieldDemo.insertOne(
...
... {
... "StudentId": 102,
... "StudentPersonalDetails": [
... {
... "StudentName": "Carol",
... "StudentAge":26
... },
... {
... "StudentName": "Bob",
... "StudentAge":21
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90a9ceb74d7cfe6392d7d9")
}
> db.getDistinctListOfSubDocumentFieldDemo.insertOne(
... {
... "StudentId": 103,
... "StudentPersonalDetails": [
... {
... "StudentName": "Bob",
... "StudentAge":25
... },
... {
... "StudentName": "David",
... "StudentAge":24
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90a9e6b74d7cfe6392d7da")
}通过 find() 方法显示来自集合的所有文档。查询如下:-
> db.getDistinctListOfSubDocumentFieldDemo.find().pretty();
输出如下:-
{
"_id" : ObjectId("5c90a9abb74d7cfe6392d7d8"),
"StudentId" : 101,
"StudentPersonalDetails" : [
{
"StudentName" : "John",
"StudentAge" : 24
},
{
"StudentName" : "Carol",
"StudentAge" : 21
}
]
}
{
"_id" : ObjectId("5c90a9ceb74d7cfe6392d7d9"),
"StudentId" : 102,
"StudentPersonalDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 26
},
{
"StudentName" : "Bob",
"StudentAge" : 21
}
]
}
{
"_id" : ObjectId("5c90a9e6b74d7cfe6392d7da"),
"StudentId" : 103,
"StudentPersonalDetails" : [
{
"StudentName" : "Bob",
"StudentAge" : 25
},
{
"StudentName" : "David",
"StudentAge" : 24
}
]
}以下是获取子文档字段值唯一列表的查询:-
> db.getDistinctListOfSubDocumentFieldDemo.distinct("StudentPersonalDetails.StudentName");输出如下:-
[ "Carol", "John", "Bob", "David" ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 程序设计
C++
C#
MongoDB
MySQL
Javascript
PHP