簡體   English   中英

在MongoDB中的嵌入式文檔中將元素插入數組

[英]Inserting an element into an Array in an embedded document in MongoDB

我對MongoDB相當陌生,並且正在我的Java項目中使用它。

我的收藏夾中包含以下文檔結構:

{ "_id":"ProcessX", "tasks":[ { "taskName":"TaskX", "taskTime":"2018-08-09T13:38:58.317Z", "crawledList":[ "http://dbpedia.org/ontology/birthYear" ] }, { "taskName":"TaskX", "taskTime":"2018-08-10T06:19:32.006Z", "crawledList":[ "http://dbpedia.org/ontology/birthYear", "http://dbpedia.org/page/Mo_Chua_of_Balla" ] }, { "taskName":"TaskY", "taskTime":"2018-08-10T06:21:58.737Z", "crawledList":[ "http://dbpedia.org/page/Mo_Chua_of_Balla" ] } ] }

我想將“ newURI”放入任務的crawledList(如果不存在)。 過程如下:

  • 使用_id =“ someProcessName”查找流程文檔
  • 在task數組中找到帶有taskName =“ someTaskName”和taskTime =“ someTaskTime”的任務文檔
  • 檢查該任務文檔的crawledList中是否存在“ newURI”
  • 如果不存在,則將newURI插入任務文檔的crawledList中

我不想將文檔檢索到內存中並使用原始Java類型(列表等)。可以使用MongoDB的Java驅動程序命令來幫助我編寫最高效的代碼嗎?

我沒有定義任何索引,因為我不知道應該定義哪些索引。 如果有更好的方法來表示它們並更快地執行此操作,我也可以更改文檔結構。

先感謝您。

因此,最后,通過閱讀Java驅動程序文檔並在網上搜索,我設法通過以下兩個功能實現了它:

public boolean crawledBefore(IRI iri) {
    return collection.countDocuments(
            and(eq("_id", CrawlProcess.getProcessName()),
                    elemMatch("tasks", and(eq("taskName", CrawlProcess.getTaskName()),
                                            eq("taskTime", CrawlProcess.getCreationTime()),
                                            in("crawledList",iri.toString()))))) != 0;
}

public void addToStore(IRI iri) {
    if(!crawledBefore(iri)) {
        collection.updateOne(
                and(eq("_id", CrawlProcess.getProcessName()),
                    elemMatch("tasks", and(eq("taskName", CrawlProcess.getTaskName()),
                                            eq("taskTime", CrawlProcess.getCreationTime())))), 
                push("tasks.$.crawledList",iri.toString()));        
    }
}

下面是它的工作原理:

crawledBefore()函數接收一個IRI並查看是否存在任何文檔; 在任務文檔中的IRI的crawledList數組中具有該IRI,該任務文檔是過程文檔中的嵌入式文檔。 具有給定流程名稱,任務名稱和時間的流程文檔始終存在於我的集合中,這里我所檢查的只是該文檔中存在IRI。

如果是這樣,第二個函數將新的IRI添加到流程文檔中該特定任務文檔的crawledList中。

干杯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM