更新mongodb中的多个文档 [英] Update multi documents in mongodb
问题描述
我在schedule
集合中有一个特定用户的3个项目,在每个记录(文档)中,我都有一个字段isActive,user
将设置为当他想从事该项目时可以为true,并且只能为一个项目设置.请参见以下记录:
I have 3 projects of a particular user in schedule
collection and in every record(document), I have field isActive, which user
will set to true when he wants to work on that project, and can set for only one project.See below records:
{
"_id" : ObjectId("5c1e0a1cd8a20917b8564e49"),
"isActive" : true,
"projectId" : ObjectId("5c0a2a8897e71a0d28b910ac"),
"userId" : ObjectId("5c0a29e597e71a0d28b910aa"),
"hours" : 1,
},
{
"_id" : ObjectId("5c1e0a1cd8a20917b8564e4a"),
"isActive" : false,
"projectId" : ObjectId("5c188a9959f6cf1258f4cb01"),
"userId" : ObjectId("5c0a29e597e71a0d28b910aa"),
"hours" : 7,
},
{
"_id" : ObjectId("5c1e0a1cd8a20917b8564e4b"),
"isActive" : false,
"projectId" : ObjectId("5cyt2a7797e71a0d25b930ad"),
"userId" : ObjectId("5c0a29e597e71a0d28b910aa"),
"hours" : 1,
}
例如,用户已完成5c0a2a8897e71a0d28b910ac
此 projectId 的工作.现在他想为5c188a9959f6cf1258f4cb01
projectId工作,所以我想编写更新查询以将5c188a9959f6cf1258f4cb01
projectId的isActive更新为true,对于5c0a2a8897e71a0d28b910ac
和5cyt2a7797e71a0d25b930ad
项目的isActive更新为false,意味着用户其他项目.>
for example, User has completed his work for 5c0a2a8897e71a0d28b910ac
this projectId. Now he wants to work for 5c188a9959f6cf1258f4cb01
projectId, So i want to write update query to update isActive to true for 5c188a9959f6cf1258f4cb01
projectId and isActive to false for 5c0a2a8897e71a0d28b910ac
and for 5cyt2a7797e71a0d25b930ad
projects, means user other projects.
推荐答案
因此,基本上,您必须使用两个查询,一个查询到$set
isActive
到false
,另一个查询到$set
isActive
到true
对于特定的userId
So basically you have to use two queries one to $set
isActive
to false
and one to $set
isActive
to true
for a particular userId
1)将isActive
设置为true
Model.update(
{ "projectId": "5c188a9959f6cf1258f4cb01", "userId": "5c0a29e597e71a0d28b910aa" },
{ "$set": { "isActive": true }}
)
2)到$set
对于同一userId
Model.update(
{ "projectId": { "$ne": "5c188a9959f6cf1258f4cb01" }, "userId": "5c0a29e597e71a0d28b910aa" },
{ "$set": { "isActive": false }}
)
这篇关于更新mongodb中的多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!