Search code examples
mongodbcsvmongodb-querymongoexport

mongoexport exclude documents


I have a MongoDB collection with the following documents. Some of the documents have 1 field and some have 2. I am interested in exporting only those with 2 fields to a CSV file. What query can I use to exclude those with 1 field?

[
{
    "id" : 1,
},

{
    "id" : 2,
},

{
   "id" : 3
   "productId": 300
}
]

my mongoexport command is: mongoexport --username x --password x --host x --db mydb --collection mycol --type=csv --fields id,productid --out "c:\myfile.csv"


Solution

  • Try this one where i have added query

    mongoexport --username x --password x --host x --db mydb --collection mycol --type=csv --fields id,productid --query '{ "$and": [ { "id": {"$exists":true}},{"productId":{"$exists":true}}] }' --out "c:\myfile.csv"
    

    Or it could be such as

    mongoexport --username x --password x --host x --db mydb --collection mycol --type=csv --fields id,productid --query '{ "id": {"$exists":true},"productId":{"$exists":true} }' --out "c:\myfile.csv"