本文介绍了mongodb mongoose-如果字段不存在,如何将文档添加到数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
像这样的文件
{
"_id" : ObjectId("5db65eb2a2f3a61fe88e162a"),
"devicesCxt" : [
{
"deviceId" : "1232",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162c"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
}
],
}
我要添加这个
{
"deviceId" : "1233",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162b"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
}
我想要这样的东西
{
"_id" : ObjectId("5db65eb2a2f3a61fe88e162a"),
"devicesCxt" : [
{
"deviceId" : "1232",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162c"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
},
{
"deviceId" : "1233",
"userAgent" : "PostmanRuntime/7.19.0",
"online" : false,
"_id" : ObjectId("5db65eb2a2f3a61fe88e162b"),
"loginAt" : ISODate("2019-10-28T03:21:22.178+0000")
}
],
}
如果不允许deviceId: 1232
,则其他deviceId: 1233
可以成功.
if deviceId: 1232
not allow,else deviceId: 1233
can succeed.
deviceId不能具有相同的对象
deviceId
在数组中应保持唯一.
deviceId
should be kept unique in the array.
我该怎么做?
推荐答案
在 deviceId
已存在传入对象. $push
Mongo查询:
const incomingDoc = {
deviceId: "1233",
userAgent: "PostmanRuntime/7.19.0",
online: false,
_id: ObjectId("5db65eb2a2f3a61fe88e162b"),
loginAt: ISODate("2019-10-28T03:21:22.178+0000")
};
db.collection.update(
{
_id: idToFilterIfAny,
"devicesCxt.deviceId": { $ne: incomingDoc.deviceId }
},
{ $push: { devicesCxt: incomingDoc } }
);
这篇关于mongodb mongoose-如果字段不存在,如何将文档添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!