MongoDB update Query in a loop - mongodb

I am working with MongoDB in one of my project. For the next feature I need to add a flag to array of objects by looping with a matching condition.
Following is an example of document that I have -
{
"_id" : ObjectId("5aaa4eb211a1c1c1f74c1657"),
"colors" : [
{ "status" : "done" },
{ "status" : "done" },
{ "status" : "n/a" }
]
}
Output should be -
{
"_id" : ObjectId("5aaa4eb211a1c1c1f74c1657"),
"colors" : [
{
"status" : "done",
"is_in_production" : true
},
{
"status" : "done",
"is_in_production" : true
},
{
"status" : "n/a"
}
]
}
I used the following query -
db.getCollection('products').update(
{
"colors.status": {
"$in":[
"done"
]
}
},
{$set: { 'colors.$[].is_in_production' :true }},
{multi: true}
)
That resulted the following error -
cannot use the part(colors of colors.$[].is_in_production)totraversetheelement({ colors: [{ "status" : "done" }, { "status" : "done" }, { "status" : "n/a" }] )}
Can someone help me with the query?? Thanks in Advance

Use updateMany together with arrayFilters to update multiple documents in an array
db.products.updateMany(
{ "colors.status": "done" },
{ $set: { "colors.$[element].is_in_production" : true}},
{ arrayFilters: [{"element.status" : "done"}]}
)

Use arrayFilters to update only a subset of embedded documents.
Try this query:
db.products.update(
{
"colors.status": {
"$in":[
"done"
]
}
},
{$set: { 'colors.$[element].is_in_production' :true }},
{multi: true, arrayFilters:[{"element.status":"done"}]}
)
Output is:
/* 1 */
{
"_id" : ObjectId("5aaa4eb211a1c1c1f74c1657"),
"colors" : [
{
"status" : "done",
"is_in_production" : true
},
{
"status" : "done",
"is_in_production" : true
},
{
"status" : "n/a"
}
]
}
Note that you need MongoDB 3.6 and need to execute on latest shell (no third party tools preferably) in order for the arrayFilters to work properly.
If the above query isn't working for your Mongo version, try this query:
db.sample.findAndModify({
query:{
"colors.status": {
"$in":[
"done"
]
}
},
update:{$set: { 'colors.$[element].is_in_production' : true }},
multi: true,
arrayFilters:[{"element.status":"done"}]
})

Related

How to search mongodb

I have two JSONs in a collection in mongodb and would like to write a bson.M filter to fetch the first JSON below.
I tried with the filter below to get the first JSON but got no result.
When the first JSON is in the collection, I get result when i use the filter
but when i have both JSONs, I do not get a result. Need help.
filter := bson.M{"type": "FPF", "status": "REGISTERED","fpfInfo.fpfInfoList.ssai.st": 1, "fpfInfo.fpfInfoList.infoList.dn": "sim"}
{
"_id" : "47f6ad68-d431-4b69-9899-f33d828f8f9c",
"type" : "FPF",
"status" : "REGISTERED",
"fpfInfo" : {
"fpfInfoList" : [
{
"ssai" : {
"st" : 1
},
"infoList" : [
{
"dn" : "sim"
}
]
}
]
}
},
{
"_id" : "347c8ed2-d9d1-4f1a-9672-7e8a232d2bf8",
"type" : "FPF",
"status" : "REGISTERED",
"fpfInfo" : {
"fpfInfoList" : [
{
"ssai" : {
"st" : 1,
"ds" : "000004"
},
"infoList" : [
{
"dn" : "sim"
}
]
}
]
}
}
db.collection.aggregate([
{
"$unwind": "$fpfInfo.fpfInfoList"
},
{
"$match": {
"fpfInfo.fpfInfoList.ssai.ds": {
"$exists": false
},
"fpfInfo.fpfInfoList.infoList.dn": "sim",
"fpfInfo.fpfInfoList.ssai.st": 1
}
}
])
Playground

How can I correctly output an array of objects in the reverse order from mongodb?

Comments are saved in an array of objects. How can I correctly output them in reverse order (comments from newest to oldest)?
My db:
{"_id":{"$oid":"5e3032f14b82d14604e7cfb7"},
"videoId":"zX6bZbsZ5sU",
"message":[
{"_id":{"$oid":"5e3032f14b82d14604e7cfb8"},
"user":{"$oid":"5e2571ba388ea01bcc26bc96"},"text":"1"
},
{"_id":{"$oid":"5e3032f14b82d14604e7cfb9"},
"user":{"$oid":"5e2571ba388ea01bcc26bc96"},"text":"2"
},
....
]
My sheme Mongoose:
const schema = new Schema({
videoId: { type: String, isRequired: true },
message: [
{
user: { type: Schema.Types.ObjectId, ref: 'User' },
text: { type: String }
},
]
});
My code:
const userComments = await Comment.find(
{ videoId: req.query.videoId },
{ message: { $slice: [skip * SIZE_COMMENT, SIZE_COMMENT] } }
)
.sort({ message: -1 })
.populate('message.user', ['avatar', 'firstName']);
but sort not working;
thanks in advance!
You can simply use $reverseArray to reverse content of an array.
db.collection.aggregate([
{
$addFields:
{
message: { $reverseArray: "$message" }
}
}
])
Collection Data :
/* 1 */
{
"_id" : ObjectId("5e3032f14b82d14604e7cfb7"),
"videoId" : "zX6bZbsZ5sU",
"message" : [
{
"_id" : ObjectId("5e3032f14b82d14604e7cfb8"),
"user" : ObjectId("5e2571ba388ea01bcc26bc96"),
"text" : "1"
},
{
"_id" : ObjectId("5e3032f14b82d14604e7cfb9"),
"user" : ObjectId("5e2571ba388ea01bcc26bc96"),
"text" : "2"
}
]
}
/* 2 */
{
"_id" : ObjectId("5e309318d02e05b694b0b25f"),
"videoId" : "zX6bZbsZ5sUNEWWWW",
"message" : [
{
"_id" : ObjectId("5e3032f14b82d14604e7cfc9"),
"user" : ObjectId("5e2571ba388ea01bcc26bc87"),
"text" : "Old"
},
{
"_id" : ObjectId("5e3032f14b82d14604e7cfd0"),
"user" : ObjectId("5e2571ba388ea01bcc26bc87"),
"text" : "New"
}
]
}
Result :
/* 1 */
{
"_id" : ObjectId("5e3032f14b82d14604e7cfb7"),
"videoId" : "zX6bZbsZ5sU",
"message" : [
{
"_id" : ObjectId("5e3032f14b82d14604e7cfb9"),
"user" : ObjectId("5e2571ba388ea01bcc26bc96"),
"text" : "2"
},
{
"_id" : ObjectId("5e3032f14b82d14604e7cfb8"),
"user" : ObjectId("5e2571ba388ea01bcc26bc96"),
"text" : "1"
}
]
}
/* 2 */
{
"_id" : ObjectId("5e309318d02e05b694b0b25f"),
"videoId" : "zX6bZbsZ5sUNEWWWW",
"message" : [
{
"_id" : ObjectId("5e3032f14b82d14604e7cfd0"),
"user" : ObjectId("5e2571ba388ea01bcc26bc87"),
"text" : "New"
},
{
"_id" : ObjectId("5e3032f14b82d14604e7cfc9"),
"user" : ObjectId("5e2571ba388ea01bcc26bc87"),
"text" : "Old"
}
]
}
Your Query : You can use native MongoDB's $lookup instead of .populate() , So try below :
Comments.aggregate([
{
$addFields:
{
message: { $reverseArray: "$message" }
}
}, {
$lookup: {
from: "User",
let: { ids: "$message.user" },
pipeline: [
{
$match: { $expr: { $in: ["$_id", "$$ids"] } }
},
{ $project: { avatar: 1, firstName: 1, _id: 0 } }
],
as: "userData"
}
}
])
You're going to want to use one of two things:
The MongoDB aggregation framework
Sorting within the application
If you choose to use the MongoDB aggregation framework, you'll likely want to use the $unwind operation to expand the array into separate documents, then sorting those documents with the $sort operation.
You can see more on how to do that in this ticket:
how to sort array inside collection record in mongoDB
You could also do this within your application by first executing a query, and then sorting each of the arrays in the result set.
Best,

Update nested array element in mongodb

In my case I have mongodb document with nested arrays and I need to update attributes array elements. My mongodb document as follows.
{
"_id" : ObjectId("5dca9c5ece5b91119746eece"),
"updatedAt" : ISODate("2019-11-20T11:48:55.339Z"),
"attributeSet" : [
{
"attributeSetName" : "test-0",
"type" : "Product",
"id" : "1574158032603",
"updatedAt" : ISODate("2019-11-19T10:10:53.783Z"),
"createdAt" : ISODate("2019-11-19T10:07:20.084Z"),
"attributes" : [
{
"attributeName" : "test-attribute",
"defaultValue" : 123,
"isRequired" : false,
"id" : "1574221129398"
},
{
"attributeName" : "test-attribute-02",
"defaultValue" : 456,
"isRequired" : false,
"id" : "1574250533840"
}
]
},
{
"attributeSetName" : "test-1",
"type" : "Product",
"id" : "1574158116355",
"updatedAt" : ISODate("2019-11-19T10:08:37.251Z"),
"createdAt" : ISODate("2019-11-19T10:08:37.251Z"),
"attributes" : []
}
]
}
I need to update element in attributes array and get the updates document into result object. This is what I tried so far.
const result = await this.model.findOneAndUpdate(
{
_id: settingsToBeUpdated._id,
"attributeSet": {
$elemMatch: {
"attributeSet.id": attributeSetId,
"attributes": {
$elemMatch: {
'attributes.id': id
}
}
}
}
},
{
$set: {
'attributeSet.$[outer].attributes.$[inner].attributeName': attributeDto.attributeName,
'attributeSet.$[outer].attributes.$[inner].defaultValue': attributeDto.defaultValue,
'attributeSet.$[outer].attributes.$[inner].isRequired': attributeDto.isRequired,
}
},
{
"arrayFilters": [
{ "outer.id": attributeSetId },
{ "inner.id": id }
]
}
);
It does not update the model. I refered to this link, but it does not help.
Any suggestion would be appreciated.
Couple of rectification required on the query, otherwise its almost there. The update is not working because $elemMatch for attributeSet (array of docs) field is to happen on id property of those docs to filter and not on attributeSet.id, it woudn't figure what it is. And nested elemMatch is not required, simply use dot notation.
To debug you can try it out with a find query.
Query (Shell):
db.collection.findOneAndUpdate(
{
_id: settingsToBeUpdated._id,
attributeSet: {
$elemMatch: {
id: attributeSetId,
"attributes.id": id
}
}
},
{
$set: {
"attributeSet.$[as].attributes.$[a].attributeName":
attributeDto.attributeName,
"attributeSet.$[as].attributes.$[a].defaultValue":
attributeDto.defaultValue,
"attributeSet.$[as].attributes.$[a].isRequired": attributeDto.isRequired
}
},
{
arrayFilters: [{ "as.id": attributeSetId }, { "a.id": id }],
returnNewDocument: true
}
);

Mongodb: is possible to returning other value from array with project using `$ne`?

Can mongo $ne return value in $project instead of true or false ?
The documents :
{
"_id" : ObjectId("5d1449db6f934a2926c175d1"),
"clients" : [
"82",
"85"
],
"roomId" : 1,
"message" : [
{
"time" : ISODate("2019-06-27T04:44:49.528Z"),
"status" : "SEND",
"text" : "Ellorad",
"sender" : "82",
"reciever" : "82",
"_id" : ObjectId("5d1449db6f934a2926c175d2")
},
{
"time" : ISODate("2019-06-27T04:44:49.528Z"),
"status" : "SEND",
"text" : "helas veronaaah",
"sender" : "82",
"reciever" : "85",
"_id" : ObjectId("5d1449ff6f934a2926c175d3")
}
]
}
What I tried :
Chat.aggregate([
{ $match: { clients: 82 } },
{
$project: {
_id: '$roomId',
receiver: { $ne: ['$clients', 82] },
message: { $slice: ['$message', -1] }
}
}
])
The result :
{
"message": [
{
"_id": 1,
"receiver": true
"message": [
{
"time": "2019-06-27T04:44:49.528Z",
"status": "SEND",
"text": "helas veronaaah",
"sender": "82",
"reciever": "85",
"_id": "5d1449ff6f934a2926c175d3"
}
]
}
]
}
So the receiver just returning true or false here, which is right considering its $ne, but the result that I want is, the receiver here to be '85' not true or false
Why dont you:
1) unwind the clients array, and
2) use $match in the next stage to exclude the undesired value(82 in this case),
3) use $project stage to get your desired result, clients will have your desired receiver.
Try this :
Chat.aggregate([
{ $match: { clients: 82 } },
{
$unwind : "clients"
},
{
$match : {
clients : {$ne : 82}
}
},
{
$project : {
_id: '$roomId',
receiver: "$clients",
message: { $slice: ['$message', -1] }
}
}
])

Update Query in MongoDB with where conditions

{
"_id" : ObjectId("510902fb7995fe3504000002"),
"name" : "Gym",
"status" : "1",
"whichs" : [
{
"name" : "American",
"status" : "1"
}
]
}
Above is my collection object.. I want to update which.name to "Indian" where which.status = 1.. Please help me with the mongoDB query for doing this..
You can try this:
db.collection.update({"whichs.status" : "1" },
{$set : { "whichs.$.name" : "Indian"},
false,
true);
This finds "whichs.status" : "1" then sets "whichs.$.name" : "Indian" for all documents. For more info on the update() method, read here.
Starting from MongoDB v3.6, you can use arrayFilters, to perform array update operation.
db.collection.update({
"whichs.status": "1"
},
{
$set: {
"whichs.$[element].name": "Indian"
}
},
{
arrayFilters: [
{
"element.status": "1"
}
]
})
Mongo Playground