27

I have a collection of the following form in MongoDB. As you can see some documends have two members "id" and "xid" and some have only 1 "id" (aside from the Object _id)

[
    {
        "id" : 1,
    },

    {
        "id" : 2,
    },

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

I want to create a mongoexport statement that exports to a csv only documents with id's AND xid's with the value of xid > 0

I currently have the following command:

mongoexport -h host -u user -p pass --db database --collection collections --csv --fields id,xid --query '{"xid":{"$ne":0}}' --out rec.csv

However this also exports documents that have an id without an xid. So i get something like

xid, id
12, 3
,4
14, 5
,3
,2
12, 5

etc.

Is there a way to export documents that only have both id and xid?

1

6 Answers 6

21

you can use below commands

mongoexport -d database_name -c collection_name --csv --query { id:{$exist:true},xid:{$gt:0}}
Sign up to request clarification or add additional context in comments.

Comments

13

You can use the following as your query:

{ $and: [
    {xid: {$exists:true}},
    {xid:{$gt:0}}
    ]  
}

$and "performs a logical AND operation on an array of two or more expressions (e.g. , , etc.) and selects the documents that satisfy all the expressions in the array."

$exists checks if the specific field is present in the document.

Also, as it is being pointed out by Vijay, in your description you mention you want xid > 0. You shouldn't be using $ne (not equal), but $gt (greater than).

Comments

5

mongoexport --db db_name --collection collection_name --query "{'Name':'Vijil'}" --out file_name.json

1 Comment

add some explanation
5

Remember as of 3.0.6 --csv tag is not supported, now in order to use that use --type=csv

Below is the query which takes MongoExport on the database db_name and collection collection_name, Remember to specify field names also(which fields you want to add in your csv file).

sudo mongoexport -d db_name -c collection_name --type=csv --query='{field1:{$gt:2}}' -f "field1,field2" --sort='{field1:-1}' -u 'username' -p 'passwd' --authenticationDatabase=admin --out dir/file.csv

Comments

4

You can change your query to

--query {id: {$exists : true}, xid: {$gt : 0}}

This above query will return only those documents that have id field and have value of xid > 0. So if there is any document that have only id field not xid, those documents will not be returned.

Comments

1

From the document given above, it seems it is an array of documents, but you are accessing the document without . notation. Seems you are accessing the document wrongly.

Should be something like '{"key.xid":{"$ne":0}}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.