私はmongodbの初心者です。重複エントリーを避ける方法を教えてください。リレーショナル テーブルでは、それを避けるために主キーを使用します。javaを使用してMongodbで指定する方法を教えてください。
7 に答える
オプションでインデックスを使用し{unique:true}
ます。
// everyone's username must be unique:
db.users.createIndex({email:1},{unique:true});
複数のフィールドでこれを行うこともできます。詳細と例については、ドキュメントのこのセクションを参照してください。
一意のインデックスにより、インデックス付きフィールドに重複する値が格納されなくなります。つまり、インデックス付きフィールドの一意性を強制します。デフォルトでは、MongoDB はコレクションの作成中に _id フィールドに一意のインデックスを作成します。
null
一意のキーから値を無視する場合は、次のオプションを追加して、インデックスをスパースにする必要があります (こちらを参照)。sparse
// everyone's username must be unique,
//but there can be multiple users with no email field or a null email:
db.users.createIndex({email:1},{unique:true, sparse:true});
MongoDB Java Driver を使用してインデックスを作成する場合。試す:
Document keys = new Document("email", 1);
collection.createIndex(keys, new IndexOptions().unique(true));
これは「_id」フィールドを使用して行うことができますが、この使用はお勧めできません。名前を一意にしたい場合は、名前を「_id」列に入れることができます。ご存知のように、「_id」列はエントリごとに一意です。
BasicDBObject bdbo = new BasicDBObject("_id","amit");
現在、コレクション内の他のエントリに「amit」という名前を付けることはできません。これは、あなたが求めている方法の 1 つです。
Mongo の v3.0 Java ドライバーの時点で、インデックスを作成するコードは次のようになります。
public void createUniqueIndex() {
Document index = new Document("fieldName", 1);
MongoCollection<Document> collection = client.getDatabase("dbName").getCollection("CollectionName");
collection.createIndex(index, new IndexOptions().unique(true));
}
// And test to verify it works as expected
@Test
public void testIndex() {
MongoCollection<Document> collection = client.getDatabase("dbName").getCollection("CollectionName");
Document newDoc = new Document("fieldName", "duplicateValue");
collection.insertOne(newDoc);
// this will throw a MongoWriteException
try {
collection.insertOne(newDoc);
fail("Should have thrown a mongo write exception due to duplicate key");
} catch (MongoWriteException e) {
assertTrue(e.getMessage().contains("duplicate key"));
}
}
Theon ソリューションは私にはうまくいきませんでしたが、これはうまくいきました:
BasicDBObject query = new BasicDBObject(<fieldname>, 1);
collection.ensureIndex(query, <index_name>, true);
私は Java プログラマーではありませんが、おそらくこれを変換できます。
デフォルトでは、MongoDB には、次のようにドキュメントが 2 回書き込まれるのを防ぐために、またはこのキーで_id
使用できる主キーがあります。upsert()
save()
var doc = {'name': 'sam'};
db.users.insert(doc); // doc will get an _id assigned to it
db.users.insert(doc); // Will fail since it already exists
これにより、重複がすぐに停止します。特定の条件下でのマルチスレッド セーフな挿入については、その場合の状態について詳しく知る必要があります。
_id
ただし、インデックスはデフォルトで一意であることを追加する必要があります。