Reputation: 41
I want to export a single field from a single collection.
Like collection name is products and field name is tag.
All tag will create new collection. I have tried this command:
mongodump --host 192.168.1.46 --port 27017 --db myDb --collection products --fields tag -o bson --out C:\Users\Desktop\tag
Upvotes: 0
Views: 1611
Reputation: 14436
So lets start by inserting some products in to our collection:
db.products.insertMany([
{ name: 'TV', tags: ['livingroom', 'electronics']},
{ name: 'Radio', tags: ['bedroom', 'electronics']},
{ name: 'Computer', tags: ['bedroom', 'electronics']}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("586bae0ec5a9a94b2674943d"),
ObjectId("586bae0ec5a9a94b2674943e"),
ObjectId("586bae0ec5a9a94b2674943f")
]
}
We can now write a simple aggreation query to go though all the documents
db.products.aggregate([
{$unwind: '$tags'},
{$group: {_id: '$tags' }},
{$out: 'productTags'}
]);
The {$unwind: '$tags'}
will deconstruct the tags array field in to a document for each tag.
Then the {$group: {_id: '$tags' }}
will group each item and create a new document for each tag.
Then the {$out: 'productTags'}
will create us a productTags collection with the output of the documents.
now if we query the productTags
collection we'll get the following output:
> db.productTags.find()
{ "_id" : "bedroom" }
{ "_id" : "electronics" }
{ "_id" : "livingroom" }
Upvotes: 1
Reputation: 833
mongodump doesn't support the selected field's backup. But you can use mongoexport/mongoimport to backup selected fields as:
mongoexport -c test --db testing -f key --out dump.json
Upvotes: 1