查询mongodb collection中唯一的文档



我需要一个查询,只从" a "收集到"B"收集。我将创建一个索引"集合,然后从";A"中复制唯一的文档。";B"收集。

"A"收藏了近3671945份文件。

"A"Collection Mongo DB Document Structure:

    {
        "_id" : ObjectId("5d654ed25616a9d461bc0a91"),
        "aC" : "AN",
        "aI" : "ABCD",
        "aN" : "000000000001",
        "aT" : "AB",
        "pD" : "2022-11-07",
        "transaction" : {
            "seqNo" : 1,
            "tC" : "S"
        }
    },
    {
        "_id" : ObjectId("5d654ed25616a9d461bc0a93"),
        "aC" : "AN",
        "aI" : "ABCD",
        "aN" : "000000000001",
        "aT" : "AB",
        "pD" : "2022-11-07",
        "transaction" : {
            "seqNo" : 1,
            "tC" : "S"
        }
    },
    {
        "_id" : ObjectId("5d654ed25616a9d461bc0a92"),
        "aC" : "AN",
        "aI" : "ABCD",
        "aN" : "000000000002",
        "aT" : "AB",
        "pD" : "2022-11-08",
        "transaction" : {
            "seqNo" : 2,
            "tC" : "S"
        }
    }
现在,我将创建我的主索引在"B"
    {
    "aC" : 1,
    "aI" : 1,
    "aN" : 1,
    "aT" : 1,
    "transaction.seqNo" : 1,
    "transaction.tC" : 1,
    "pD" : 1
    }

你能帮我查询唯一的文档从"A"收集到"B"在"B"上启用的基于索引的集合;收集?

查询需要帮助

提前感谢。

执行$group$first,每个组选择一个文档。保存$$ROOT,后续替换为保存的$$ROOT。最后使用$merge保存到集合b

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        "aC": "$aC",
        "aI": "$aI",
        "aN": "$aN",
        "aT": "$aT",
        "seqNo": "$transaction.seqNo",
        "tC": "$transaction.tC",
        "pD": "$pD"
      },
      doc: {
        $first: "$$ROOT"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$doc"
    }
  },
  {
    "$merge": {
      "into": "B",
      "on": "_id",
      "whenMatched": "replace"
    }
  }
])

Mongo Playgroun

旁注:您可能希望在创建索引之前执行插入操作,以提高写速度。

相关内容

  • 没有找到相关文章

最新更新