Database Reference
In-Depth Information
Now let's look at a handful of examples that illustrate how to use this command. The
first example finds the document you're searching for and removes it once it is found:
> db.media.findAndModify( { "Title" : "One Piece",sort:{"Title": -1},
remove:
true} )
{
"_id" : ObjectId("4c445218c603000000007ede"),
"Type" : "Manga",
"Title" : "One Piece",
"Volumes" : 612,
"Read" : 524
}
This code returned the document it found matching the criteria. In this case, it found
and removed the first item it found with the title “One Piece.” If you execute a find()
function now, you will see that the document is no longer within the collection.
The next example modifies the document rather than removing it:
> db.media.findAndModify( { query: { "ISBN" : "987-1-4302-3051-9" }, sort:
{"Title":-1}, update: {$set: {"Title" : " Different Title"} } } )
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 }
 
Search WWH ::




Custom Search