我有一個像下面這樣的檔案:
{
myDocument:
{
_id: (Auto-generated)
someField: "Hello world",
targetField: ["Steve", "Bill"]
}
}
另外,我有一個這樣的存盤庫:
@Repository
public interface FooRepository extends MongoRepository<MyDocument, String> {
}
我的問題是:“如何在 targetField 中添加新資料而不在本地找到它?因為如果我的串列太大,我不想加載它,而只想在其中插入一些新資料。”
謝謝。
uj5u.com熱心網友回復:
$addToSet
db.collection.update({
_id: "1"
},
{
"$addToSet": {
targetField: {
$each: [
"Steve",
"Sam"
]
}
}
},
{
new: true
})
mongoplayground
uj5u.com熱心網友回復:
使用MongoTemplate,Query并Update通過spring data mongodb
Update.addToSet將專案添加到集合(不可復制)Update.push將專案附加到陣列(可復制)
import org.springframework.data.mongodb.core.*;
@Autowired
MongoTemplate mongoTemplate;
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(idToUpdate));
Update update = new Update();
update.addToSet("targetField", "newValue");
mongoTemplate.updateFirst(query, update, "collectionName");
- 要獲取結果檔案,請使用
FindAndModifyOptions
FindAndModifyOptions options = FindAndModifyOptions.options()
.returnNew(true);
TargetClass result = mongoTemplate.findAndModify(query, update, options, TargetClass.class, "collectionName");
- 添加多個值
update.addToSet("targetField")
.each("value1", "value2");
update.push("targetField")
.each("value1", "value2");
- 洗掉專案
position
update.pop("targetField", position);
- 洗掉專案
value
update.pull("targetField", "value");
- 洗掉多個專案
update.pullAll("targetField", new Object[]{"value1", "value2"});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360466.html
