$push and $inc error when performing updateOne in Mongoose - mongodb

Express.js is using Mongoose. I want to put the value in a particular document array and add the index value to +1.
I wrote the code as below.
await DocSchema.updateOne({ userId : <userId> }, {
$push : {
dataArr : {
$inc : { index : 1},
name : <username>,
age : <userage>
}
}
});
In addition, the field type of the model was set as follows:
...
dataArr : [
{
index : {
type : Number,
required : true,
unique : true
},
...
}
]
...
No error occurs when performing the actual query, but the index value is not visible. How should I modify the code?

Related

Updating document with object field

I am new to MongoDB, learning from its documentation but can't find a way to update the document field using MongoDB shell
When I tried to insert the "cancellation" object with either field the query works fine.
db.inventory.update({},
{
$set : { "cancellation":
{
{"date" : new Timestamp()},
{"reason" : "null"}
}
}
},
{upsert : false,multi : true})
It shows
"SyntaxError: invalid property id #(shell)"
on executing this query
Your query is wrong. Try this:
db.inventory.update({},{$set : { "cancellation":
{
"date" : new Timestamp(),
"reason" : "null"
}
} },{upsert : false,multi : true})

Updating mongo document after it's been found

I'm trying to update a number of documents from an array of object ids passed. I want to be able to update each document by pushing the userid into the visitor array.
i'm getting this error CastError: Cast to ObjectId failed for value. see my code below
var estates = req.params.estates.split(',');
Estate.findByIdAndUpdate({ _id: { $in: estates } }).then(function(Estate)
{
Estate.visitors.push(mongoose.Types.ObjectId( req.params.userid));
Estate.save();
});
according to mongoose documentations findByIdAndUpdate first param is an id which you are passing an object
try replacing it by findOne({ _id: { $in: estates } })
Your API usage is wrong, first argument for findByIdAndUpdate should be an id, it fails to cast array to id.
for matching and updating multiple documents,
you need to use updateMany
db.foo.updateMany({"_id" : { $in : [1,2,3] }},{$push : {test: 2}},{$upsert : false})
or update with multi : true option
db.store.update({"_id" : { $in : [1,2,3] }},{$push : {test: 2}},{$upsert : false, multi : true})
output
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 0 }
Mongoose
Estate.update({ _id: { $in: estates } }, {$push : {visitors : req.params.userid}}, {multi : true, upsert : false})
Doc findByIdAndUpdate

check if value exists in array field in mongodb

I want to check if user id exists inside an array field of mongodb (using meteor)
db.posts.find().pretty()
{
"_id" : "hT3ezqEyTaiihoh6Z",
"body" : "hey\n",
"authorId" : "AyJo5nf2Lkdqd6aRh",
"createdAt" : ISODate("2016-05-13T06:19:34.726Z"),
"updatedAt" : ISODate("2016-05-13T06:19:34.726Z"),
"likecount" : 0,
"already_voted" : [ ] }
db.posts.find( { _id:"hT3ezqEyTaiihoh6Z"},{ already_voted: { $in : ["AyJo5nf2Lkdqd6aRh"]} }).count()
1
It gives count value 1 , where as I am expecting it to be 0 .
Your logic is fine. Just the syntax is wrong.
db.posts
.find({
_id: "hT3ezqEyTaiihoh6Z",
already_voted: { $in: ["AyJo5nf2Lkdqd6aRh"] },
})
.count();
This should work.
You can just simply use count method. Don't need to use two operation like Find and then count.
db.posts
.count({
_id: "hT3ezqEyTaiihoh6Z",
already_voted: { $in: ["AyJo5nf2Lkdqd6aRh"] }
});

Nested mongo query

Here is what the data looks like:
{
"_id" : {
"item" : "1",
"state" : "something"
},
"things" : {
"ordered" : 2,
"cost" : 123
}
}
I try to query for all doc of item 1, there are many state for that item. I know i can get that record using db.orders.find({_id:{item:"1", state: "something"}}). But I would like to get all states I try something like db.orders.find({_id:{item:"1", state: {$exists: true}}})
But that doesn't seem to work. What am i doing wrong?
If you want to get the list of all the different states you could use.
db.orders.distinct("_id.state");
If you want to get the list of all the states in your collection
db.orders.find({}, {"_id.state": 1});
I really want to get the things.cost for all the states for a given
item
db.orders.aggregate([
{ $group : {
_id : { item : "$_id.item" , state : "$_id.state"},
cost: { $push : "$things.cost" }
}
}
]);
If you want the sum instead of the elements of the group by use $sum instead of $push
How do i get for certain item?
db.orders.aggregate([
{ $match : { "_id.item" : "YOUR_ID" }},
{ $group : {
_id : { item : "$_id.item" , state : "$_id.state"},
cost: { $push : "$things.cost" }
}
}
]);

One operation for Update if value doesn't exists in an array using mongodb

I'm wondering if it is possible with just one operation (or just one command) to update a document inside mongodb if the value used in the update doesn't exists in an array.
example mongodb document:
{
regs : {
someid : 12345,
dataArray : [ { id : 1 }, { id : 43 }, { id : 11 }]
}
}
Now I want only to update if the id inside dataArray is not in use already, something like:
db.regs.update({ someid : 12345 }, { $push : { dataArray : { id : INT }}})
Using the above line it's possible to check if { id : INT } is alreay in my array and update only if it isn't?
In a couple of ways. For example you can use query matching document of interest:
db.regs.update(
{someid : 12345, 'dataArray.id': {$ne: INT}},
{$push : { dataArray : {id : INT }}}
)
or perform update using addToSet:
db.regs.update(
{someid : 12345},
{$addToSet : {dataArray : {id : INT }}}
)
As #zero323 has already pointed out, there is an specific update operation with that specific use case in mind. From the MongoDB documentation:
$addToSet
The $addToSet operator adds a value to an array only if the value is
not in the array already. If the value is in the array, $addToSet
returns without modifying the array.
Consider the following example:
db.collection.update( { field: value }, { $addToSet: { field: value1 } } );
Here, $addToSet appends value1 to the array stored in field,
only if value1 is not already a member of this array.