Database Reference
In-Depth Information
The preceding example updates the title from “Definitive Guide to MongoDB,” The to “Different Title”—and
returns the old document (as it was before the update) to your shell. If you would rather see the results of the update
on the document instead, you can add the new operator after your query:
> db.media.findAndModify( { query: { "ISBN" : "987-1-4302-3051-9" }, sort:
{"Title":-1}, update: {$set: {"Title" : " Different Title"} }, new:true } )
Note that you can use any modifier operation with this command, not just $set .
Renaming a Collection
It might happen that you discover you have named a collection incorrectly, but you've already inserted some data into
it. This might make it troublesome to remove and read the data again from scratch.
Instead, you can use the renameCollection() function to rename your existing collection. The following example
shows you how to use this simple and straightforward command:
> db.media.renameCollection("newname")
{ "ok" : 1 }
If the command executes successfully, an OK will be returned. If it fails, however (if the collection doesn't exist,
for example), then the following message is returned:
{ "errmsg" : "assertion: source namespace does not exist", "ok" : 0 }
The renameCollection command doesn't take many parameters (unlike some commands you've seen so far);
however, it can be quite useful in the right circumstances.
Removing Data
So far we've explored how to add, search for, and modify data. Next, we'll examine how to remove documents, entire
collections, and the databases themselves.
Previously, you learned how to remove data from a specific document (using the $pop command, for instance).
In this section, you will learn how to remove full documents and collections. Just as the insert() function is used for
inserting and update() is used for modifying a document, remove() is used to remove a document.
To remove a single document from your collection, you need to specify the criteria you'll use to find the
document. A good approach is to perform a find() first; this ensures that the criteria used are specific to your
document. Once you are sure of the criterion, you can invoke the remove() function using that criterion as a
parameter:
> db.newname.remove( { "Title" : "Different Title" } )
This statement removes the topic added previously or any other item in your collection that has the same title.
The fact this statement removes all topics by that title is one reason why it's best to specify the item's _id value—it's
always unique.
Or you can use the following snippet to remove all documents from the newname library (remember, we renamed
the media collection this previously):
> db.newname.remove({})
 
Search WWH ::




Custom Search