MongoDb replaceOne() but wanted few field - database

in case of replaceOne() --> it replace whole object by new object -->what if i want few field of old object as it and replace that object by new object

replaceOne will replace the whole document and update with the one you are replacing you need to use updateOne instead this will only update specific fields which you wanted rest fields will be as it is
For example
db.restaurant.updateOne(
{ "name" : "Central Perk Cafe" },
{ $set: { "violations" : 3 }},
{upsert:true}
);
here upsert:true option will help in inserting new documents if it doesn't exist you can read more about it here https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/

you can use update
if you document is {name:"company",country:"India",owner:"me"}
db.company.update({
_id:*id*
},
{$set:{
name:"mycompany",
country:"United Kingdom"}})

Related

MongoDB/PyMongo find_one_and_update and/or find() method doesn't find specified entry, just appends to the end of the collection

I'm attempting to search in an array in my collection, to find by a key named "id". Both the find() method and find_one_and_update() don't return the entry I'm trying to find. The collection is structured like so:
"_id" : {stuff},
"events":[{
"id":"12345",
"date":"01/01"
}, {
"id":"12346",
"date":"02/02"
}]
Trying find() as:
result = db.get_collection("events").find({"events.id" : "12345"})
for item in result:
print(item)
Prints out the entire collection.
Trying to update a specific entry by its id like so will append it to the end.
db.get_collection("events").find_one_and_update({"events.id" : "12345"},{"$set" : {"date" : "somedate"}})
Looks like this afterwards:
"id":"12346",
"date":"02/02"
}], "date" : "somedate"
So, what am I doing wrong with updating and finding here? Every other person seems to have no trouble with this part.
Figured this out on my own, needed to specify which object + field to update in the collection:
db.get_collection("events").find_one_and_update({"events.id" : "12345"},{"$set" : {"events.$.date" : "somedate"}})

How to efficiently update part of a mongodb record?

In mongodb, if I have a user record like this
{
_id:1,
name:"John",
items : [
{wid:1, type:"basic"},
{wid:1, type:"rare"}
]
}
And I want to update the name of rare to uncommon. How can I efficiently do it? My concern is if that array was 1 million length, do I need to push that huge array (which includes the new update somewhere in it) in the update call when I add, update or delete something from it? Is there a way I can be more efficient only push the delta change?
Thanks
I want to update the name of rare to uncommon
You can do that. In your example, you can pass type:rare in the condition and use arrayFilters to update.
Bulk find with arrayfilters to update only what needs to be updated
Refer this
db.collection.update(
{ <query selector> },
{ <update operator>: { "array.$[<identifier>].field" : value } },
{ arrayFilters: [ { <identifier>: <condition> } } ] }
)
do I need to push that huge array (which includes the new update somewhere in it) in the update call when I add, update or delete something from it?
Not necessarily. You can update as mentioned above.
You can add easily using $push.
You can delete using $pull.

How to add new items to an array in MongoDB

I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that when I tested by hard-coding sample table info onto here, it wasn't adding more items to that array, but simply replacing the entire array with whatever values I had here.
function addlist(name, item, id){ // Add to user's list
console.log(id);
db.collection('newcon').update({_id: id}, { "$set": { "$push": { name:item } } });
ret(id);
}
$set is not an array update operation.
The $set operator replaces the value of a field with the specified value.
You just want to use $push by itself, as in
.update({_id: id}, {$push: {name: item}})
You can't interpolate object property names in raw object declarations, so if you want to use a variable name you will have to create an object to do this:
var obj = {};
obj[name] = item;
You can then pass this to .update, {$push: obj}

Can Solr DIH do atomic updates?`

With Solr 4 came the ability to do atomic (partial) updates on existing documents within the index. I.e. one can match on the document ID and replace the contents of just one field, or add further entries to multivalued fields: http://wiki.apache.org/solr/Atomic_Updates
Can atomic updates be done from DataImportHandler (DIH)?
The answer is "yes" with the ScriptTransformer, I discovered through trial and error.
The Solr documentation shows how to add an update attribute to a field node with "set", "add" or "inc". If I create a test XML file with the requisite update attribute, it works fine when passed to the regular update handler. But, when passed to DIH - even without any transformation - the update attributes get ignored completely.
Here's a simplified version of the script transformer I used to reintroduce the update attribute and get atomic updates working. Note the use of the Java HashMap.
var atomicTransformer = function (row) {
var authorMap = new java.util.HashMap();
var author = String(row.get('author'));
authorMap.put('add', author);
row.put('author', authorMap);
};
This produces the following JSON in DIH debug mode:
{
"id": [
123
],
"author": [
{
"add": "Smith, J"
}
]
}
Multivalued fields are also no problem: pass in an ArrayList to the HashMap instead of a string.
var atomicTransformer = function (row) {
var fruits = new java.util.ArrayList();
fruits.add("banana");
fruits.add("apple");
fruits.add("pear");
var fruitMap = new java.util.HashMap();
fruitMap.put('add', fruits);
row.put('fruit', fruitMap);
}

MongoDB: Query and retrieve objects inside embedded array?

Let's say I have the following document schema in a collection called 'users':
{
name: 'John',
items: [ {}, {}, {}, ... ]
}
The 'items' array contains objects in the following format:
{
item_id: "1234",
name: "some item"
}
Each user can have multiple items embedded in the 'items' array.
Now, I want to be able to fetch an item by an item_id for a given user.
For example, I want to get the item with id "1234" that belong to the user with name "John".
Can I do this with mongoDB? I'd like to utilize its powerful array indexing, but I'm not sure if you can run queries on embedded arrays and return objects from the array instead of the document that contains it.
I know I can fetch users that have a certain item using {users.items.item_id: "1234"}. But I want to fetch the actual item from the array, not the user.
Alternatively, is there maybe a better way to organize this data so that I can easily get what I want? I'm still fairly new to mongodb.
Thanks for any help or advice you can provide.
The question is old, but the response has changed since the time. With MongoDB >= 2.2, you can do :
db.users.find( { name: "John"}, { items: { $elemMatch: { item_id: "1234" } } })
You will have :
{
name: "John",
items:
[
{
item_id: "1234",
name: "some item"
}
]
}
See Documentation of $elemMatch
There are a couple of things to note about this:
1) I find that the hardest thing for folks learning MongoDB is UN-learning the relational thinking that they're used to. Your data model looks to be the right one.
2) Normally, what you do with MongoDB is return the entire document into the client program, and then search for the portion of the document that you want on the client side using your client programming language.
In your example, you'd fetch the entire 'user' document and then iterate through the 'items[]' array on the client side.
3) If you want to return just the 'items[]' array, you can do so by using the 'Field Selection' syntax. See http://www.mongodb.org/display/DOCS/Querying#Querying-FieldSelection for details. Unfortunately, it will return the entire 'items[]' array, and not just one element of the array.
4) There is an existing Jira ticket to add this functionality: it is https://jira.mongodb.org/browse/SERVER-828 SERVER-828. It looks like it's been added to the latest 2.1 (development) branch: that means it will be available for production use when release 2.2 ships.
If this is an embedded array, then you can't retrieve its elements directly. The retrieved document will have form of a user (root document), although not all fields may be filled (depending on your query).
If you want to retrieve just that element, then you have to store it as a separate document in a separate collection. It will have one additional field, user_id (can be part of _id). Then it's trivial to do what you want.
A sample document might look like this:
{
_id: {user_id: ObjectId, item_id: "1234"},
name: "some item"
}
Note that this structure ensures uniqueness of item_id per user (I'm not sure you want this or not).

Resources