合并猫鼬中的字段

时间:2018-08-30 15:45:59

标签: mongoose merge field

我目前的猫鼬是

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}]

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

1 个答案:

答案 0 :(得分:0)

由于您的输出不是有效的JSON,而不是对象/数组,因此我冒昧地假设这样的事情:

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"
  }
]

您可以see it here