大家好,我正在嘗試用葡萄酒建立一個社交網路。對于我的應用程式,我使用的是 MongoDB 和 Neo4J。在我的檔案資料庫中,我正在存盤葡萄酒,并且對于我存盤在里面的每種葡萄酒,就像嵌套檔案一樣,所有相關的評論。
葡萄酒有這些屬性
反而
Wine_Reviews 有這些屬性
如果我不更改 Wines 的值,MongoDB 創建一個檔案,并且所有相關的評論都像該酒的嵌套檔案 (RIGHT) 一樣插入,但是如果我更改酒的一個屬性,例如“Province”,MongoDB 將創建兩個檔案,所以兩個酒即使標題相同。 錯誤的情況
我的問題是:是否有可能避免這種情況?即使同一酒的所有其他屬性發生變化,在一個檔案中插入所有具有相同標題的酒?(僅當屬性相同時才能正常作業)
正確的情況,但這里的葡萄酒屬性不會因插入的評論而改變
這是 Crud_mongo.java 的代碼:
public void createWine(String title, String variety, String country, String province, int price, String taster_name, Integer points,
String description, String taster_twitter_handle, String country_user, String e_address, Boolean admin) {
final MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
MongoDatabase database = mongoClient.getDatabase("Wines");
MongoCollection<Document> collection = database.getCollection("wines");
Document wine = new Document("title", "" title "")
.append("title", "" title "")
.append("variety", "" variety "")
.append("country", "" country "")
.append("province", "" province "")
.append("price", "" price "");
Document user = new Document("taster_name", "" taster_name "")
.append("score", "" points "")
.append("description", "" description "")
.append("taster_twitter_handle", "" taster_twitter_handle "")
.append("country", "" country_user "")
.append("email", "" e_address "")
.append("admin", "" admin "");
MongoCursor<String> cursormedia = collection.distinct(title, String.class).iterator();
MongoCursor<String> cursor = collection.distinct("_id.title", String.class).iterator();
UpdateOptions options = new UpdateOptions().upsert(true);
Bson filter = Filters.eq(wine);
Bson setUpdate = Updates.push("wine_reviews", user);
collection.updateMany(filter, setUpdate, options);
System.out.println("Successfully inserted review. \n");
}
uj5u.com熱心網友回復:
當前(錯誤)行為與您的_id. _id必須是唯一的,并且除了title您有 4 個其他欄位組成此復雜鍵之外province,如果您更改其他 4 個欄位中的任何一個,則會創建一個新檔案。
_id將資料庫內部鍵(如)與業務/資料域鍵(如標題和其他一些屬性)分開總是好的。我建議您讓 MongoDB 驅動程式負責_id在插入時構建并將其他欄位移出正確的檔案,例如
{
_id: ObjectId('61e190fc3105a836ad0dc8b1'),
title: "VINO",
variety: "Rosato",
country: "Germania",
province: "a",
price: 50,
reviews: [
{taster_name: "Prova1", score: 50 ...
您現在可以輕松更新:
db.collection.update({_id:ObjectId('61e190fc3105a836ad0dc8b1')},{$set: {province:"b"}});
_id是唯一的,因此它只會更新一個檔案。如果您選擇使用其他標準進行更新,它可能會或可能不會更新多個檔案,但您可以控制它。例如,假設 title variety country不是唯一的,并且您希望所有此類葡萄酒都在省“b”,然后使用以下multi選項:
db.collection.update({title:'VINO',variety:'Rosato',country:'Germania')},
{$set: {province:"b"}},
{multi:true});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/411686.html
標籤:
