MongoDB: aggregate $project add field with static value

前端 未结 2 1313
死守一世寂寞
死守一世寂寞 2020-12-18 18:01

Can I somehow add custom field with static (not computed) value?

I want to prepare objects before send and I need to remove some fields with internal information and

相关标签:
2条回答
  • 2020-12-18 18:47

    Note that $literal was implemented in Mongo 2.6. So now you can simply write:

    db.test.aggregate(
       {$project: {_id: 0, data: 1, entity_id: {$literal: 54}}})
    

    See $literal.

    0 讨论(0)
  • 2020-12-18 18:51

    edit as of 2.6 the $literal expression exists so you don't have to use the workaround now.

    Original answer: I know this may sound really dumb, but you can use a "no-op" expression to "compute" what you need.

    Example:

    db.test.aggregate( { $project : {_id:0, data:1, entity_id: {$add: [54]} } } )
    

    There was a proposed $literal operator for exactly this use case but it hasn't been implemented yet, you can vote for it here.

    0 讨论(0)
提交回复
热议问题