jsondatabasemongodbmongoexport

MongoExport: Can you query a field?


I am currently working on a solution using Mongo database. We must use MongoExport for this one. Is there a way to enhance my MongoExport command to include a filter on the fields?

For instance: -q:"{"Status": "COMPLETE"}" -f:Id,EanCode,Channels:{"$elemMatch":{"ChannelId":"Test"}

Update: Hello again, by suggestion in the comments I am adding am example document.

Document:

{
  "Id": "1"
  "Status": "COMPLETE",
  "EanCode": "1234567890",
  "Barcode": "100100100",
  "Name": "Test Product",
  "Channels": [
    {
      "ChannelId": "Test"
    },
    {
      "ChannelId": "Dumbeldore"
    }
  ]
}

Result:

{
  "Id": "1"
      "Status": "COMPLETE",
      "EanCode": "1234567890",
      "Channels": [
        {
          "ChannelId": "Test"
        }
      ]
}

I can use any tool you suggest, might space out from the MongoExport. But the important thing is that It must be optimized and export JSON Objects.

Thank you for your attention and help :)


Solution

  • Option 1. I think you cannot do with mongoexport directly , but you can do via aggregation:

     echo 'db.test.aggregate([{$match:{Status:"COMPLETE","Channels.ChannelId":"Test"} },{$addFields:{Channels:{ $filter: { input: "$Channels", as: "ch", cond: {$eq:["$$ch.ChannelId","Test"] }  } }} } ])' | mongo --authenticationDatabase admin  --port 27017 -u test -p xxxx --quiet > out.json
    

    playground1

    Option 2: You output from aggregation to a output collection via $out and then you mongoexport.

    playground2