【问题标题】:Inserting an element into an Array in an embedded document in MongoDB在 MongoDB 的嵌入式文档中将元素插入到数组中
【发布时间】:2018-08-23 20:10:03
【问题描述】:

我对 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" 查找流程文档
  • 在 tasks 数组中找到 taskName = "someTaskName" 和 taskTime = "someTaskTime" 的任务文档
  • 检查该任务文档的 crawledList 中是否存在“newURI”
  • 如果不存在,则将newURI插入到任务文档的crawledList中

我不想将文档检索到内存中并使用原始 Java 类型(列表等)。您能帮助我使用 MongoDB 的 Java 驱动程序命令编写最有效的代码吗?

我没有定义任何索引,因为我不知道应该定义哪些索引。 如果有更好的方法来表示它们并更快地执行此操作,我还可以更改文档结构。

提前谢谢你。

【问题讨论】:

    标签: java mongodb document


    【解决方案1】:

    所以最后通过阅读Java Driver文档并在网上搜索,我设法实现了以下两个功能:

    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 中。

    干杯。

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 2016-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 2022-01-17
      • 2021-03-24
      相关资源
      最近更新 更多