1

ありがとうございました

  • この質問をクリックしていただきありがとうございます。私はこれを可能な限り徹底的にするために最善を尽くしました。
  • それでも、さらに明確にする必要がある場合は、お気軽にお知らせください。
  • 質問が長すぎると思われる場合。3 番目と 4 番目の部分を読んで、独自のソリューションをここに投稿してください。

設定

  • Mongodb Java ドライバー: org.mongodb:mongo-java-driver:3.11.0-rc0

私がしたいこと

  • 特定の「名前」フィールドを持つ特定のドキュメントを検索します。
  • 次に、他のフィールドまたはドキュメント全体を更新します。

文書例

// the document that I am trying to find in db
{
  "_id":"5de6af7cfa42833bd9849477",
  "name":"Richard Koba",
  "skills":[]
}

// the document that I have
{
  "name":"Richard Koba",
  "skills":[jump, dance, sing]
}

// final result in db
{
  "_id":"5de6af7cfa42833bd9849477",
  "name":"Richard Koba",
  "skills":[jump, dance, sing]
}

私が今していること

  // finding a document with same "name" field as input doc and update it with doc
  public MongoCollection updateDocument(Document doc, String colName) {
    MongoCollection collection;

    // make sure collection exist
    try {
      collection = connectCollection(colName); // returns MongoCollection Obj
    } catch (CollectionNotFoundException e) {
      MessageHandler.errorMessage(e.getMessage());
      return null;
    }

    // trying to find the document.
    if (collection.find(eq("name", doc.get("name"))).first() == null) {
      // if document not found, insert a new one
      collection.insertOne(doc);
    } else {
      // if the document found, replace/update it with the one I have
      collection.replaceOne(eq("name", doc.get("name")), doc);
    }

    return collection;
  }

私の誤った解決策について私が見つけたこと

  1. collection.find(eq("name", doc.get("name"))).first()null を返すことはありません。
  2. Javaは、オブジェクトを返すとだけ言っています。MongoDB のドキュメントによると、それは でありTResult、これは を指していMongoIterable<TResult>ます。私はここで立ち往生しています。
  3. コードの結果は、最終的にどのドキュメントも挿入/更新されないということです。

参照

4

2 に答える 2

0
  1. collection.find()ドキュメントの配列を返します。ここで実際に欲しいのはcollection.findOneAndUpdate()

  2. TDoucmentからオブジェクトを取得した後、Jackson などのObjectMapperfindOneAndUpdateを使用して、それを Java オブジェクトにマップし直すことができます。

于 2019-12-04T02:17:49.533 に答える