首页 > 解决方案 > 合并猫鼬中的字段

问题描述

我现在的猫鼬是

var selectDetail =person.find({_id:'the id of the person'})
    .select('person.first_name person.last_name')
       .exec(function(err, result){
        if(!err){
            console.log(result)
            }
       })

生产

[{ person:   { first_name: 'Samuel', last_name: 'Sharon'},  _id: 5b84c718bcc9d9114c34bf0a },
{ person:   { first_name: 'Jesse',   last_name: 'James'},   _id: 5b86fcdf583643014489261b },
{ person:   { first_name: 'Solomon',   last_name: 'Saunders'},   _id: 5b86fcdf583643014489261b },
{ person:   { first_name: 'Blake',   last_name: 'hill'},   _id: 5b86fcdf583643014489261b }]

生产

[{79ahjhhajhga986786a78ajg, Samuel Sharon},
{5sghjkhs798s798sg798s98g, Jesse James},
{56fghjajhga678hj6877866v, Solomon Saunders},
{2364jhadhkjdaf76ajhdfa76, Blake Hill}]

我正在认真寻找出路 我对我之前写的内容进行了一些修改

标签: mongoosemergefield

解决方案


由于您的输出不是有效的 JSON 而不是 Object/Array 我冒昧地假设这样的事情:

db.collection.aggregate([
  {
    $addFields: {
      "info": {
        $concat: [
          "$_id",
          " ",
          "$person.first_name",
          " ",
          "$person.last_name"
        ]
      }
    }
  },
  {
    $project: {
      _id: 0,
      "person": 0
    }
  }
])

这会给你:

[
  {
    "info": "5b84c718bcc9d9114c34bf0a Samuel Sharon"
  },
  {
    "info": "4b86fcdf583643014489261b Jesse James"
  },
  {
    "info": "1b86fcdf583643014489261b Solomon Saunders"
  },
  {
    "info": "2b86fcdf583643014489261b Blake hill"
  }
]

你可以在这里看到


推荐阅读