how to remove quotations for ObjectId imported from csv - mongodb

I have imported a csv file into a collection,
My document saved like
"_id" : "ObjectID(53874d952f92e2af1a5f0afb)"
I was unable to query this
Can anyone help me to remove quotations for ObjectId

Lets assume your collection name is myCollection.
Do this :
db.myCollection.forEach(function(doc) {
var oldId = doc._id;
var newIdStr = doc._id.replace(/ObjectID\((\w+)\)/g,"\$1");
var newObjId = ObjectId(newIdStr);
doc._id = newObjId;
db.myCollection.save(doc);
db.myCollection.remove({_id:oldId});
});

CSV does not fully preserve the types of your fields and can present strings and integers (not Object_ids). If I were you, I would write an a parser in the most suitable language and convert your _id in objectIds there.
Another approach (if your _ids are not important) you can change _id in csv header to any other name and during the import mongo will create new ids, then you will go and remove your created field.
Next time you can use mongodump and mongorestore to preserve the types.

Related

MongoDB: How to query over a json string?

There's a MongoDB collection that was populated with documents like this one:
{
"_id" : ObjectId("5b7f83b591fae49715443590"),
"content" : "{\n\t\"email\":\"username#domain.com\",\n\t\"country_code\": \"US\"\n}"
}
As you can see "content"has a JSON string
I was able to parse the string using JSON.parse() like:
db.getCollection('my_collection').find({}).map(function(doc){ return {'_id':doc._id, 'content': JSON.parse(doc.content)}});
Giving me an array of objects with _id and content as an object.
Is there a way to execute queries (filtering, aggregate functions) over content preferably without getting an array from map?
like you said In terms of the database content is a string. So you need to save the entire collection where content will be a object so you will be able to filtering, aggregate etc...

Referencing property in mongoDB by taking _id

I have a collection which have a document like this:
collection 1
{
_id: ObjectID(),
name: foo
}
I would get ObjectID of the above collection and copy into a document of another collection in order to reference correctly. Should I do simply:
db.collection1.find({name:"foo"},{_id:1})
EDIT
A call to find will return a cursor. Cursors works like an iterator in other languages. You can either attempt to find the first element in the cursor using the next() function and then get it's _id property or simplify your statement using findOne:
var x = db.collection1.findOne({name:"foo"}, {_id:1});
var id = x._id;
This is making an assumption that you are getting a document back from that query. You'll probably want to add a null check on x before grabbing the _id property.

updating Mongoose documents with nested arrays at multiple indexes

I'm having trouble updating a schema with a nested array to have one objectID in multiple rows of the array. Please help if you can!
My Schema looks like this:
var ProblemSchema = new Schema({
data : "etc..."
array1 : [{
_id : { type: 'String' },
array2: [{ type: Schema.Types.ObjectId}]
}]}
I can easily add an objectId to a SINGLE nested array using the $ operator in the update object like so:
var query = {array1._id : ID};
var update = {$push : {'array1.$.array2' : objectId}};
Problem.update(query, update)
I want to be able to, however, add the same objectId to MULTIPLE array2s (i.e. corresponding to different array1 ids) in one query, but the $ operator only matches to the first match to the query so I can't do it the way outlined above.
I'm also trying to avoid having a for loop on the server (I realize I could find() the correct document then use a for loop in which I manually push() the objectID to the correct array2s but the solution involves large overhead), can anyone think of a solution?
As of MongoDB 2.6, there's no way to do this with with a single update query. The $ positional operator is a placeholder for the first matching element in an array. There's a MongoDB feature request for updating all matching elements of an array, SERVER-1243, that you can track in the meantime.

duplicate mongo record in same collection

In mongo I have a collections with records. These record are very complex. Now I would like to duplicate one of them.
I can easily select the one
mongo> var row = db.barfoo.find({"name":"bar"});
Now I actually don't know what to do. I don't know what is in row because I cannot find a way to print its content. How can I change specific properties and finally insert this modified row again
mongo> db.barfoo.insert(row);
thnx
You must change value _id - generate new:
var row = db.barfoo.findOne({"name":"bar"});
row._id = ObjectId();
db.barfoo.insert(row);
Good Luck!
I am going to assume that you're working directly inside the mongo shell.
Once you have your document (not a row :P ), you'd modify the properties in the same way you would a normal JavaScript object:
var doc = db.barfoo.findOne( { "name": "bar" } );
doc.name = "Mr Bar";
Note that the find() command returns a cursor, so if you're looking to extract a single document, you should use the findOne() function. This function returns a single document.
If you are interested in duplicating numerous documents, you can use the find() function and iterate over the cursor to retrieve each document:
db.barfoo.find( { "name": "bar" } ).forEach( function( doc ){
doc.name = "Mr Bar";
}
After you change the relevant properties, you can use the insert/save methods to persist the data back to mongo. Don't forget to change/delete the _id attribute so that you'll actually create a new document.
As a side note, in order to view the contents of an object in the mongo shell, you can use the print() function. If you want a more visually appealing output, you could use printjson().

Finding all records containing a given subfield in mongodb

In mongodb, i can find all those records in a collection in database db that contain a particular field using the following query
var doc = db.collection_name.find({field_name:{$exists:true}})
Now consider the following document:
{
"somefield":"someval",
"metadata": {"id":"someval",
"client_url":"http://www.something.com"
}
}
What would be the query for getting all records having the id field in metadata ?
Please Help.
Thank You
You can use dot notation to reference sub-document fields
var doc = db.collection_name.find({"metadata.id":{$exists:true}})