0

We have this syntax with SQL server:

select name as 'database',
      'I_Love_SQL' as 'feelings'
from sys.databases

which will return results like this:

database    |   feelings
database1   |   I_Love_SQL
database2   |   I_Love_SQL
database3   |   I_Love_SQL
database4   |   I_Love_SQL

How can I achieve this with mongoDB? I have this query and I need to add some fixed fields for example ACTIVE, PT-BR, etc.

db.product.find({
    "company.cad": {
        $in: [" ", "14940"]
    },
    "tradeItemMeasurements.netContent.measurementUnitCode": {
        $ne: null
    }
}, {
    "_id": 1,
    "brandNameInformation.brandName": 1,
    "childTradeItems.gtin": 1,
    "company.cad": 1,
    "placeOfProductActivity.countryOfOrigin.countryCode": 1,
    "referencedFileInformations.uniformResourceIdentifier": 1,
    "tradeItemClassification.gpcCategoryCode": 1,
    "tradeItemDescriptionInformation": 1,
    "tradeItemMeasurements.netContent": 1,
    "tradeItemMeasurements.width.measurementUnitCode": 1
}).limit(1)
1

You can use MongoDB's Aggregation Pipeline to add calculated or constant fields to a query.

The $addFields stage appends new fields to existing result documents if you don't want to specify a list of all fields. However, since your example projects a subset of fields you can also add new fields using expressions in a $project stage.

Your find() query would become a $match stage in aggregation. Here's an example showing a few different options (with comments) in the $project stage:

db.product.aggregate([

    // The initial $match stage can take advantage of available indexes
    { $match: {
        "company.cad": {
            $in: [" ", "14940"]
        },
        "tradeItemMeasurements.netContent.measurementUnitCode": {
            $ne: null
        },
    }},

    // Project the desired result fields
    { $project: {
        // Fields that already exist
        "_id": 1,
        "brandNameInformation.brandName": 1,
        "childTradeItems.gtin": 1,
        "company.cad": 1,
        "placeOfProductActivity.countryOfOrigin.countryCode": 1,
        "referencedFileInformations.uniformResourceIdentifier": 1,
        "tradeItemClassification.gpcCategoryCode": 1,

        // constant values
        "ACTIVE": true,
        "language.code": "PT-BR",

        // calculated values (in this case, size of an array)
        "itemCount": { $size: "$tradeItems" },

        // literal values (that might otherwise be interpreted as expressions)
        "batch.batchNumber": { $literal: 1 },
    }}

])
  • Amazing. Thanks. – Racer SQL Jul 26 at 17:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.