mongodb java数组_将数组值添加到MongoDB中,其中元素不在数组中

在MongoDB中,这是我的 account 文档的简化结构:

{

"_id" : ObjectId("5a70a60ca7fbc476caea5e59"),

"templates" : [

{

"name" : "Password Reset",

"content" : "AAAAAAAA"

},

{

"name" : "Welcome Message",

"content" : "BBBBBB"

}

]

}

有一个类似的 default_templates 集合

let accnt = await Account.findOne({ _id: req.account._id }, { templates: 1 });

let defaults = await DefaultTemplate.find({}).lean();

我的目标是在帐户下找到丢失的模板,并从默认值中获取它们 . (a)我需要upsert templates 如果它没有想要更新模板(如果它已经存在于帐户中) .

我尝试过以下方法:

if (!accnt.templates || accnt.templates.length < defaults.length) {

const accountTemplates = _.filter(accnt.templates, 'name');

const templateNames = _.map(accountTemplates, 'name');

Account.update({ _id: req.account._id, 'templates.name' : { $nin: templateNames } },

{ '$push': { 'templates': { '$each' : defaults } } }, { 'upsert' : true },

function(err, result) {

Logger.error('error %o', err);

Logger.debug('result %o', result);

}

);

}

这在upsert中成功,但即使 templateNames 中有匹配的名称,它也会输入所有默认模板 . 我已经验证 templateNames 数组是正确的,我也尝试使用 $addToSet 而不是 $push ,所以我不能理解Mongo子网查询 .

关于我做错了什么的任何想法?

编辑:我通过在更新之前简单地从默认数组中删除元素来实现这一点,但我仍然想知道如何使用Mongoose实现这一点 .

在使用Java将JSON文档数组插入MongoDB时,你需要使用BSON工具将JSON转换为BSON格式。以下是一个示例代码,可以将JSON数组插入到MongoDB: ``` import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import java.util.ArrayList; import java.util.List; public class MongoDBTest { public static void main(String[] args) { // 创建MongoDB连接 MongoClient client = new MongoClient("localhost", 27017); // 获取MongoDB数据库 MongoDatabase database = client.getDatabase("test"); // 获取MongoDB集合 MongoCollection<Document> collection = database.getCollection("users"); // 创建JSON数组 String json = "[{ \"name\" : \"Tom\", \"age\" : 20 },{ \"name\" : \"Jerry\", \"age\" : 25 }]"; // 将JSON数组转换为BSON文档列表 List<Document> documents = new ArrayList<>(); JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(json).getAsJsonArray(); for (JsonElement jsonElement : jsonArray) { Document document = Document.parse(jsonElement.toString()); documents.add(document); } // 插入BSON文档列表到MongoDB集合 collection.insertMany(documents); // 关闭MongoDB连接 client.close(); } } ``` 在这个示例,我们使用了JsonParser将JSON字符串转换为JsonArray,然后遍历JsonArray,将每个元素转换为BSON文档,并将文档添加到BSON文档列表。最后,我们使用insertMany方法将BSON文档列表插入到MongoDB集合。注意,在使用BSON工具时,需要注意BSON格式与JSON格式的差异。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值