Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb aggregation with $project to conditionally exclude a field

I would like to exclude a field from a mongo db aggergtion pipeline, after reading the docs, I thought I needed to specify either 1 or 0 to keep the field or not (cf. http://docs.mongodb.org/manual/reference/operator/aggregation/project/)

So I tried the following (using node.js mongoose, but the syntax is quite the same as plain mongo):

aggregate.match({ date: { $gte : today } });
aggregate.sort('-date');
aggregate.group({
    _id: '$name',
    date: { $first: '$date' },
    user: { $first: '$user' },
    app: { $first: '$app' }
});
aggregate.project({
    _id: 1,
    last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', 0 ] },
    user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', 0 ] },
    app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', 0 ] }
});

But doing that, I end with documents like this:

[ 
  {
    _id: 'devices',
    user: 0,
    app: 0,
    last: 0
  },
  { 
    _id: 'undo',
    user: 'test',
    app: 'truc',
    last: Mon Jan 26 2015 16:21:53 GMT+0100 (CET)
  }
]

I want the user, app and date to appear only when _id is undo.

How to achieve it?

Thanks!

like image 309
xavier.seignard Avatar asked Jan 26 '15 15:01

xavier.seignard


People also ask

How do I exclude fields in MongoDB?

To exclude the _id field from the output documents of the $project stage, specify the exclusion of the _id field by setting it to 0 in the projection document.

How do I get only certain fields in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What does $project do in MongoDB?

The $project function in MongoDB passes along the documents with only the specified fields to the next stage in the pipeline. This may be the existing fields from the input documents or newly computed fields.


1 Answers

Starting in mongoDB 3.6, you can use the REMOVE variable to exclude fields conditionally.

In your particular case, the project stage should look like this:

aggregate.project({
    _id: 1,
    last: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$date', '$$REMOVE' ] },
    user: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$user', '$$REMOVE' ] },
    app: { $cond: [ { $eq : [ '$_id', 'undo' ] }, '$app', '$$REMOVE' ] }
});
like image 172
David Avatar answered Nov 15 '22 20:11

David