Mongo Collection 구조
컬렉션명 : bookstore{
"_id": "1234567890",
"books": [
{
"bookId": "1",
"storeList": ["용산", "구로", "신도림A", "신도림B"]
},
{
"bookId": "2",
"storeList": ["서울역", "영등포A"]
},
{
"bookId": "3",
"bookNm": "재건축",
"storeList": ["강남", "개포동"]
}
]
}
1. books element 추가
Monogo Query:
db.getCollection('bookstore').update(
{ _id: "1234567890" },
{ $push: { books: { bookId: "4", storeList: [ "신사", "대학로", "신촌" ] } } }
)
MongoTemplate:
var query = Query.query(Criteria.where("_id").is("1234567890"));
var update = new Update();
var book = new Book();
book.setBookId("4")
book.setStoreList(Arrays.asList("신사", "대학로", "신촌"));
update.push("books", book);
mongoTemplate.updateFirst(query, update, "bookstore");
2. books element 삭제
Monogo Query:
db.getCollection('bookstore').update(
{ _id: "1234567890" },
{ $pull: { books: { bookId: "4" } } }
)
MongoTemplate:
var query = Query.query(Criteria.where("_id").is("1234567890"));
var pullQuery = new Query();
pullQuery.addCriteria(Criteria.where("bookId").is("4"));
var update = new Update();
update.pull("books", pullQuery);
mongoTemplate.updateFirst(query, update, "bookstore");
3. storeList의 element 추가 - 값이 없는 경우에만
Monogo Query:
db.getCollection('bookstore').update(
{ _id: "1234567890", books: { $elemMatch: { bookId: "3" } } },
{ $addToSet: { "books.$.storeList": "신사동" } }
)
MongoTemplate:
var query = new Query();
var criteria = Criteria.where("_id").is("1234567890")
.and("books").elemMatch(Criteria.where("bookId").is("3"));
query.addCriteria(criteria);
var update = new Update();
update.addToSet("books.$.storeList", "신사동");
mongoTemplate.updateFirst(query, update, "bookstore");
4. storeList의 element 삭제
Monogo Query:
db.getCollection('bookstore').update(
{ _id: "1234567890", books: { $elemMatch: { bookId: "3" } } },
{ $pull: { "books.$.storeList": "신사동" } }
)
MongoTemplate:
var query = new Query();
var criteria = Criteria.where("_id").is("1234567890")
.and("books").elemMatch(Criteria.where("bookId").is("3"));
query.addCriteria(criteria);
var update = new Update();
update.pull("books.$.storeList", "신사동");
mongoTemplate.updateFirst(query, update, "bookstore");
5. storeList의 element 변경
Monogo Query:
db.getCollection('bookstore').updateOne(
{_id: "1234567890", books: {$elemMatch:{bookId: "3"}}},
{$set: {"books.$.bookNm": "재개발"}}
)
MongoTemplate:
var query = new Query();
var criteria = Criteria.where("_id").is("1234567890")
.and("books").elemMatch(Criteria.where("bookId").is("3"));
query.addCriteria(criteria);
var update = new Update();
update.set("books.$.bookNm", "재개발");
mongoTemplate.updateFirst(query, update, "bookstore");
0 Comments:
댓글 쓰기