MongoDb - Add object into array only if that object's id is not present in array object id.

Use Case : Check schema, If you want to add new object into "data" array and you want to check if that new object's id is present or not in array, If present then add to data array, If not present then don't add.

Ex. You want to check your new object's id like "dataId" OBJ - { dataId : 5, dataIcon : "xyz" } matches with user 1 and data.someObj.dataId . If not found then you can add new obejct like this into data - { someObj : { dataId : 5, dataIcon : "xyz" } , description : { userName : "kkk", userData : "some data" } }.

Schema : Users

[ { _id : 1,

name : "raj",

data : [ { someObj : { dataId : 1, dataIcon : "xyz" } ,

description : { userName : "abc", userData : "some data" }

} ,

{ someObj : { dataId : 2, dataIcon : "xyz" } ,

description : { userName : "abc", userData : "some data" }

} , ]

} ,

{ _id : 2,

name : "alex",

data : [ { someObj : { dataId : 1, dataIcon : "xyz" } ,

description : { userName : "abc", userData : "some data" }

} ,

{ someObj : { dataId : 2, dataIcon : "xyz" } ,

description : { userName : "abc", userData : "some data" }

} , ]

}

]

const newObject = { dataId : 5 , description : "again somedata" }

JS Code -

const user = await Users.updateOne( {

? ? ? ? ? ? _id : userId,

? ? ? ? ? ? "data.someObj.dataId" : { $ne : newObject.dataId }

? ? ? ? }, {

? ? ? ? ? ? $push : {

? ? ? ? ? ? ? ? data : newObject

? ? ? ? ? ? }

? ? ? ? }, { upsert: true }).

Done.

要查看或添加评论,请登录

Swaraj Jadhav的更多文章

社区洞察

其他会员也浏览了