在数组内部使用ensureIndex()
并设置unique:1。让我们创建一个包含文档的集合-
> db.demo298.save({Name: 'Chris', Marks: [46, 79] }); WriteResult({ "nInserted" : 1 }) > db.demo298.save({Name: 'David', Marks: [67, 88] }); WriteResult({ "nInserted" : 1 }) > db.demo298.ensureIndex({ Marks: 1 }, {unique: 1}); { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo298.save({Name: 'Mike', Marks: [88,98] }); WriteResult({ "nInserted" : 0, "writeError" : { "code" : 11000, "errmsg" : "E11000 duplicate key error collection: test.demo298 index: Marks_1 dup key: { : 88.0 }" } })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo298.find();
这将产生以下输出-
{ "_id" : ObjectId("5e4d56e55d93261e4bc9ea48"), "Name" : "Chris", "Marks" : [ 46, 79 ] } { "_id" : ObjectId("5e4d56f55d93261e4bc9ea49"), "Name" : "David", "Marks" : [ 67, 88 ] }