$split并将对象数组的第一个元素作为新对象返回到mongodb查询中的主集合

jfewjypa  于 2023-11-17  发布在  Go
关注(0)|答案(1)|浏览(184)

我有一个包含许多对象的集合。我需要从现有对象的数据在main中创建一个新对象,并将引用ID添加到现有对象。请帮助。

{
        "_id": "officeLocation",
        "data": [
            {
             "_id": ObjectId("2233),
             "key": "APAC - ANZ" 
             "value": "APAC - ANZ" 
            },
            {
             "_id": ObjectId("21323),
             "key": "APAC - Japan" 
             "value": "APAC - Japan" 
            },
            {
             "_id": ObjectId("2221233),
             "key": "EMEA - CE - Benelux - Brussels" 
             "value": "EMEA - CE - Benelux - Brussels" 
            },
            {
             "_id": ObjectId("2221233),
             "key": "EMEA - CE - Benelux - London" 
             "value": "EMEA - CE - Benelux - London" 
            },
           ]
     }

字符串
像这样,我需要拆分key值的第一部分,并将新的Object添加到名为region的集合中,并将它的id作为引用id添加到现有的officeLocation中。

预期结果:

{
        "_id": regions,
        "data" [
            {
              "_id" : ObjecteId(123),
              "key" : APAC
              "value": APAC
            },
            {
              "_id" : ObjectId(1234),
              "key" : EMEA
              "value": EMEA
            }
    
         ]
      },
      {
       "_id": "officeLocation",
       "data": [
            {
             "_id": ObjectId("2233),
             "key": "APAC - ANZ" 
             "value": "APAC - ANZ" 
             "referenceId" : ObjectId(123)
            },
            {
             "_id": ObjectId("21323),
             "key": "APAC - Japan" 
             "value": "APAC - Japan",
             "referenceId" : ObjectId(123) 
            },
            {
             "_id": ObjectId("2221233),
             "key": "EMEA - CE - Benelux - Brussels" 
             "value": "EMEA - CE - Benelux - Brussels",
             "referenceId" : ObjectId(1234)
            },
            {
             "_id": ObjectId("2221233),
             "key": "EMEA - CE - Benelux - London" 
             "value": "EMEA - CE - Benelux - London",
             "referenceId" : ObjectId(1234)
            },
           ]
      }


首先需要使用正则表达式进行拆分--使用mongodb查询从键中取出正确的区域。
请帮帮我

qlvxas9a

qlvxas9a1#

只需要$split和' - '作为前缀,$first就可以得到区域。

db.collection.aggregate([
  {
    "$match": {
      "_id": "officeLocation"
    }
  },
  {
    "$unwind": "$data"
  },
  {
    "$set": {
      "region": {
        "$first": {
          "$split": [
            "$data.key",
            " - "
          ]
        }
      }
    }
  },
  {
    "$group": {
      "_id": "regions",
      "regions": {
        "$addToSet": {
          "_id": new ObjectId(),
          "key": "$region",
          "value": "$region"
        }
      }
    }
  },
  {
    "$merge": {
      "into": "collection",
      "on": "_id"
    }
  }
])

字符串
Mongo Playground

相关问题