我使用MongoDB作为我的数据库。我在每个文档中有52个Fields / BsonElement / FieldNames。在我的收藏中,包含数百万个文档。
我的应用程序使用.NET,有一个组合框/下拉控件,可让用户选择一个唯一的主键/字段。我想知道如何检查字段是否有任何重复值。如果有,我将不会在我的组合框控件中包含它。
答案 0 :(得分:2)
我们可以在聚合管道中使用groupby来计算所有唯一字段,然后将它们与总文档进行比较。
说我们有以下数据:
[
{
"_id":ObjectId("59dc805cf51b821565695ec8"),
"isDeleted": false,
"salutation": "Mr.",
"firstName": "Kevin",
"lastName" : "Smith"
},{
"_id":ObjectId("59dc80d5f51b821565695ec9"),
"isDeleted": true,
"salutation": "Miss",
"firstName": "Helen",
"lastName" : "Smith"
},{
"_id":ObjectId("59dc80dff51b821565695eca"),
"isDeleted": false,
"salutation": "Mr.",
"firstName": "Joe",
"lastName" : "Bloggs"
}
]
然后我们可以运行以下查询:
db.test.aggregate([
{
$group: {
_id : null,
total: {$sum: 1},
isDeleted: {$addToSet: "$isDeleted"},
salutation: {$addToSet: "$salutation"},
firstName: {$addToSet: "$firstName"},
lastName: {$addToSet : "$lastName"},
},
},{
$project: {
isDeleted: { $eq: [ "$total", {$size: "$isDeleted"} ]},
salutation: { $eq: [ "$total", {$size: "$salutation"} ]},
firstName: { $eq: [ "$total", {$size: "$firstName"} ]},
lastName: { $eq: [ "$total", {$size: "$lastName"} ]}
}
}
]);
这将返回一个包含每个字段的所有可能值的文档:
{
"_id" : null,
"isDeleted" : false,
"salutation" : false,
"firstName" : true,
"lastName" : false
}
答案 1 :(得分:0)
答案 2 :(得分:0)
感谢Kevin Smith的回答,我能够完成它。干杯!〜
.NET
等价物:
`Dim Aggregate = Collection.Aggregate.
Group(New BsonDocument From {
{"_id", BsonNull.Value},
{"total", New BsonDocument From {
{"$sum", 1}}},
{"isDeleted", New BsonDocument From {
{"$addToSet", "$isDeleted"}}}}
).
Project(
New BsonDocument From {
{"isDeleted", New BsonDocument From {
{"$eq", New BsonArray From {
"$total", New BsonDocument From {
{"$size", "$isDeleted"}}}}}}}
)`