如何在mongodb/mongoose中使用$ addToSet之前检查其他数组是否包含我要添加的值?
问题描述:
我想检查其他'集'是否有我想要添加的值。如果另一组具有该值,则将其从该组中移除并将其添加到新组。 { "_id": "5a052785aa06c22429717bad", "word": "wordtest5", "__v": 0, "pronunciations": [ { "pronunciation": "wordtest1", "_id": "5a052785aa06c22429717bae", "likes": [ "remove_this", "5a0508cfcf4f6620786a3cb1" ], "rating": 1 }, { "pronunciation": "wordtest5", "_id": "5a0674c1053ae929db3a576c", "likes": [], "rating": 1 }, { "pronunciation": "testing5", "_id": "5a06770346be3d2ac6f31561", "likes": [ "remove_this", "5a0508cfcf4f6620786a3cb1", ], "rating": 1 } ] }
我想删除每个'likes'数组中的所有'remove_this'字符串。
答
使用$关于你提到的其他“套”拉和您要添加的实际设置使用$ addToSet。这样你就可以实现你想要的。
下一次,请对你的问题非常清楚。
嗨,我发布了一个例子,并尝试了'Word.findOneAndUpdate({word},{$ pull:{'pronunciations':{'likes':userId}}},{multi:true})'但不能让它去除元素。 – earthyearth