Mongodb copy a collection into an other collection - mongodb

I need to copy a collection into an other collection to work with. What I have so far is
checkPoints.find().forEach(function(copy){'pdiCheckPoints'[MachineNr].insert(copy);});
But mongo throws the TypeError: Cannot call method 'insert' of undefined.
The copy works with
checkPoints.find().forEach(function(copy){pdiCheckPoints.insert(copy);});
but working with more than 1 Machine i need to add an id for each copy somehow.
Any help is highly appreciated.

You can simply augment your document with an additional key during the copy:
checkPoints.find().forEach(function(doc){
doc.machineNumber = MachineNr;
pdiCheckPoints.insert(doc);
});

i think this is help to u
db.oldCollection.aggregate([{$out : "newCollection"}])

Related

Renaming a Collection Using Pymongo

I realize that a collection can be renamed in MongoDB using
db["old_name"].renameCollection("new_name")
But is there an equivalent in PyMongo? I tried the following, but it didn't work either.
db["old_name"].rename_collection("new_name")
According to the documentation, the method is simply named rename.
rename(new_name, session=None, **kwargs)
new_name: new name for this collection
session (optional): a ClientSession
**kwargs (optional): additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. dropTarget=True)
May be you can use rename in pymongo, just use
db.oldname.rename('newname')
You can check the link:
https://api.mongodb.com/python/current/api/pymongo/collection.html?highlight=rename
An admin command to rename a collection can be executed in like manner.
query = {
'renameCollection': '<source_namespace>',
'to': '<target_namespace>',
}
client.admin.command(query)
query = bson.son.SON([
('renameCollection', 't1.ccd'),
('to', 't2.ccd2'),
])
print(query)
self.mgclient.admin.command(query)
Need to use bson.son.SON, as dict is unordered. Please refer to:
http://api.mongodb.com/python/current/api/bson/son.html#bson.son.SON
http://api.mongodb.com/python/current/api/pymongo/database.html
Note the order of keys in the command document is significant (the
“verb” must come first), so commands which require multiple keys (e.g.
findandmodify) should use an instance of SON or a string and kwargs
instead of a Python dict.

MongoDB findOneAndReplace log if added as new document or replaced

I'm using mongo's findOneAndReplace() with upsert = true and returnNewDocument = true
as basically a way to not insert duplicate. But I want to get the _id of the new inserted document (or the old existing document) to be passed to a background processing task.
BUT I also want to log if the document was Added-As-New or if a Replacement took place.
I can't see any way to use findOneAndReplace() with these parameters and answer that question.
The only think I can think of is to find, and insert in two different requests which seems a bit counter-productive.
ps. I'm actually using pymongo's find_one_and_replace() but it seems identical to the JS mongo function.
EDIT: edited for clarification.
Is it not possible to use replace_one function ? In java I am able to use repalceOne which returns UpdateResult. That has method for finding if documented updated or not. I see repalce_one in pymongo and it should behave same. Here is doc PyMongo Doc Look for replace_one
The way I'm going to implement it for now (in python):
import pymongo
def find_one_and_replace_log(collection, find_query,
document_data,
log={}):
''' behaves like find_one_or_replace(upsert=True,
return_document=pymongo.ReturnDocument.AFTER)
'''
is_new = False
document = collection.find_one(find_query)
if not document:
# document didn't exist
# log as NEW
is_new = True
new_or_replaced_document = collection.find_one_and_replace(
find_query,
document_data,
upsert=True,
return_document=pymongo.ReturnDocument.AFTER
)
log['new_document'] = is_new
return new_or_replaced_document

Mongodb: How to drop a collection named "stats"?

I created a collection named "stats" but whenever I try to delete it by using db.stats.drop() cmd line. It shows an error.
TypeError: db.stats.drop is not a function
Even tried this.
db["stats"].drop
Any solution?
if the collection exists db.stats.drop() should work (depending on the mongodb version maybe) or else perhaps db.getCollection("stats").drop();
but if all else fails, run: db.runCommand({drop : "stats"}) this should drop it if it exists without any error at least.

Can not delete collection from mongodb

Can not delete the collection from the shell,
The thing that the collection is available and my php script is accessing it (selecting|updating)
But when I used:
db._registration.drop()
it gives me an error:
Date, JS Error: TypeErrorL db._registration has no properties (shell): 1
The problem is not with deleting the collection. The problem is with accessing the collection. So you would not be able to update, find or do anything with it from the shell. As it was pointed in mongodb JIRA, this is a bug when a collection has characters like _, - or .
Nevertheless this type of names for collections is acceptable, but it cause a problem in shell.
You can delete it in shell with this command:
db.getCollection("_registration").drop()
or this
db['my-collection'].drop()
but I would rather rename it (of course if it is possible and will not end up with a lot of changing).
You can also use:
db["_registration"].drop()
which syntax works in JS as well.
For some reason the double quotes "_registration" did not workfor me .. but single quote '_registration' worked

Zend db table find just like fetchRow

I´m using find() to retrieve a value from the database, but It returns an array with the objects, I would like that it return to me just the object like fetchRow returns, is there any change or similar thing to do?
Thanks, and best regard´s.
Well, It was so simple, for those that are in doubt, the solution is:
Zend_Loader::loadClass('News');
$db = new News();
$row = $db->find($id)->current();
That´s it, thanks.