1
我是一個使用MongoDB的n00b,希望清理我們的地址數據庫。我們有多個文件可以有相同的地址。所有的地址都被統一格式化,不存在拼寫或縮寫問題,但我一直無法弄清楚如何只在集合中插入唯一地址。使用MongoDB存儲唯一地址
db.testing.createIndex({ address: 1 }, { unique: true });
db.testing.update(
{address:
{
street: "99 Main Street",
city: "Boston",
zip: "66666"
}},
{ upsert: true});
db.testing.update(
{address:
{
street: "99 Main Street",
city: "Boston",
zip: "66666"
}},
{ upsert: true});
db.testing.update(
{address:
{
street: "199 Main Street",
city: "Boston",
zip: "66666"
}},
{ upsert: true});
db.getCollection('testing').find({});
以上應該只輸出2個地址。
如果不存在,我該如何獲取它,否則跳過而不拋出錯誤? – Brad
將該場景添加到答案中。 –