How to export the fields of an embedded document in mongodb - mongodb

My doc:
db.org.insert({
"id" : 28,
"organisation" : "Mickey Mouse company",
"country" : "US",
"contactpersons" : [{
"title" : "",
"typecontact" : "D",
"mobilenumber" : "757784854",
"firstname" : "Mickey",
"lastname" : "Mouse",
"emailaddress" : "mickey#mouse.com"
},
{
"title" : "",
"typecontact" : "E",
"mobilenumber" : "757784854",
"firstname" : "Donald",
"lastname" : "Duck",
"emailaddress" : "donald#duck.com"
}],
"modifieddate" : "2013-11-21T16:04:49+0100"
});
My query:
mongoexport --host localhost --db sample --collection org --type csv --fields country,contactpersons.0.firstname,contactpersons.0.emailaddress --out D:\info_docs\org.csv
By this query, I'm able to get only the first document values of the contactpersons.But, I'm trying to export the second document values also.
How can I resolve this issue ? Can anyone please help me out regarding this ...

You're getting exactly the first document in contactpersons because you are only exporting the first element of the array (contactpersons.0.firstname). mongoexport can't export several or all elements of an array, so what you need to do is to unwind the array and save it in another collection. You can do this with the aggregation framework.
First, do an $unwind of contactpersons, then $project the fields you want to use (in your example, country and contactpersons), and finally save the output in a new collection with $out.
db.org.aggregate([
{$unwind: '$contactpersons'},
{$project: {_id: 0, org_id: '$id', contacts: '$contactpersons', country: 1}},
{$out: 'aggregate_org'}
])
Now you can do a mongoexport of contacts (which is the result of the $unwind of contactpersons) and country.
mongoexport --host localhost --db sample --collection aggregate_org --type=csv --fields country,contacts.firstname,contacts.emailaddress --out D:\info_docs\org.csv

Related

Mongodb export with conditional logic?

I want to export "street" : "Downstreet 34" But dont export, if the source value is other than 3
Sample 1 JSON
"addresses" : [ {"source" : 3 , "street" : "Downstreet 34"}]
Export "street" : "Downstreet 34"
Sample 2 JSON
"addresses" : [ {"source" : 2 , "street" : "Downstreet 34"}]
Dont export "street" : "Downstreet 34"
mongoexport --db db_name --collection collection_name --query '{source : 3 , street : "Downstreet 34"}' --out output_file.json
This should run - update the query statement as required. Make required simple changes if not working.
db.collection.find(
{ source: 2 },
{ street: 1}
)
Example that you can use to build queries like these are : source
# SQL QUERY
SELECT user_id, status
FROM users
WHERE status = "A"
#mongoDB Query
db.users.find(
{ status: "A" },
{ user_id: 1, status: 1, _id: 0 }
)

Concat 2 mongodb collections

I'm trying to combine 2 collections into one (not join). I have 2 databases with same collections and collection structure.
As example:
Collection test1 db1:
{
"_id" : ObjectId("574c339b3644a65b36e77359"),
"appName" : "App1",
"customerId" : "Client1",
"environment" : "PROD",
"methods" : []
}
Collection test2 db2:
{
"_id" : ObjectId("574c367d627b45ef0abc00e5"),
"appName" : "App2",
"customerId" : "Client2",
"environment" : "PROD",
"methods" : []
}
I'm trying to create the following:
One collection test db, where the documents will be merged from test1 and test2 but not one with each other. What would be the proper way to achieve this?
{
"_id" : ObjectId("574c339b3644a65b36e77359"),
"appName" : "App1",
"customerId" : "Client1",
"environment" : "PROD",
"methods" : []
},
{
"_id" : ObjectId("574c367d627b45ef0abc00e5"),
"appName" : "App2",
"customerId" : "Client2",
"environment" : "PROD",
"methods" : []
}
The complexity is that ID are referenced in other collection of mongo.
the fastest way will be to create a dump (using mongodump) and restore them at once (example is using windows paths).
mongodump --db test1 --collection test1 --out c:\dump\test1
mongodump --db test2 --collection test2 --out c:\dump\test2
mongorestore --db test3 --collection test3 c:\dump\test1
mongorestore --db test3 --collection test3 c:\dump\test2

mongo export array elements

I would like to export 3 different csv files, here is my document
{
"capacities" : [
{
"size" : "A",
"incoming_parcels" : 27,
"outgoing_parcels" : 0,
"empty_compartments" : 0
},
{
"size" : "B",
"incoming_parcels" : 11,
"outgoing_parcels" : 0,
"empty_compartments" : 8
},
{
"size" : "C",
"incoming_parcels" : 2,
"outgoing_parcels" : 1,
"empty_compartments" : 7
}
]
}
I would like to get all documents where capacities[1] = B and then get all fields - same for all sizes.
Here is my syntax for export :
mongoexport.exe --db name --collection name --type csv --out sizeB.csv -q "{'capacities.1.size': 'B'}" -f size,incoming_parcels,outgoing_parcels,empty_compartments
I've also tried -f capacities.1.size etc
One approach you could take is to use the aggregation framework to filter your documents using the above query as your $match operator and then write the documents returned by the aggregation pipeline to a specified collection using the $out operator. You can then export the data from that aggregation output collection. The following outlines the concept:
db.test.aggregate([
{
"$match": {
"capacities.size": "B"
}
},
{
"$unwind": "$capacities"
},
{
"$match": {
"capacities.size": "B"
}
},
{
"$project": {
"size" : "$capacities.size",
"incoming_parcels" : "$capacities.incoming_parcels",
"outgoing_parcels" : "$capacities.outgoing_parcels",
"empty_compartments" : "$capacities.empty_compartments",
}
},
{
"$out": "capacities_output"
}
])
Export to csv:
mongoexport.exe --db name --collection "capacities_output" --csv > sizeB.csv --fields size,incoming_parcels,outgoing_parcels,empty_compartments

Export array of documents from MongoDB in csv

I'm working on a java program to pass from MongoDB to Neo4j.
I have to export some Mongo documents in a csv file.
I have, for example, this document:
"coached_Team" : [
{
"team_id" : "Pal.00",
"in_charge" : {
"from" : {
"day" : 25,
"month" : 9,
"year" : 2013
}
},
"matches" : 75
}
]
I have to export in csv. I read some other questions, for example this and I used that tip to export my document.
To export in csv I use this command:
Z:\path\to\Mongo\3.0\bin>mongoexport --db <database> --collection
<collection> --type=csv --fields coached_Team.0.team_id,coached_Team.0.in_charge.from.day,
coached_Team.0.in_charge.from.month,coached_Team.0.in_charge.from.year,
coached_Team.0.matches --out "C:\path\to\output\file\output.csv
But, it did not work for me:

MongoDB GeoNear Aggregate

The question is:
Consider the following location: [-72, 42] and the range (circle) of radius 2 around this point. Write a query to find all the states that intersect this range (circle). Then, you should return the total population and the number of cities for each of these states. Rank the states based on number of cities.
I have written this so far:
db.zips.find({loc: {$near: [-72, 42], $maxDistance: 2}})
and a sample output of that is:
{ "city" : "WOODSTOCK", "loc" : [ -72.004027, 41.960218 ], "pop" : 5698, "state" : "CT", "_id" : "06281" }
In SQL i would simply do a group by "state", how would i be able to do that here while also counting all the cities and total population?
assuming you follow the mongoimport routine for its zipcode data (i brought mine into a collection called zips7):
mongoimport --db mydb --collection zips7 --type json --file c:\users\drew\downloads\zips.json
or
mongoimport --db mydb --collection zips7 --type json --file /data/playdata/zips.json
(depending on your OS and paths)
then
db.zips7.ensureIndex({loc:"2d"})
db.zips7.find({loc: {$near: [-72, 42], $maxDistance: 2}}).forEach(function(doc){
db.zips8.insert(doc);
});
note that db.zips7.stats() shows like 30k rows and zips8 has 100 rows
db.zips8.aggregate( { $group :
{ _id : "$state",
totalPop : { $sum : "$pop" },
town_count:{$sum:1}
}}
)
{
"result" : [
{
"_id" : "RI",
"totalPop" : 39102,
"town_count" : 10
},
{
"_id" : "MA",
"totalPop" : 469583,
"town_count" : 56
},
{
"_id" : "CT",
"totalPop" : 182617,
"town_count" : 34
}
],
"ok" : 1
}
Syntax in mongoid
Zips.where(:loc => {"$within" => {"$centerSphere"=> [[lng.to_f,lat.to_f],miles.to_f/3959]}})
Example:
Zips.where(:loc => {"$within" => {"$centerSphere"=> [[-122.4198185,37.7750454],2.0/3959]}})