MongoDB数组操作

1.数组查询

//scores
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
//[80,85)区间
db.scores.find(
   { results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
//包含88
db.scores.find(
   { results: { $elemMatch: { $eq: 80 } } }
)

2. 对象数组查询

//survey
{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

//查询score = 8
db.survey.find(
    { "results": { $elemMatch : { "score" : 8}}}
)
//或者
db.survey.find(
    { "results": { $elemMatch : { "score" : {$eq : 8}}}}
)
//当只有一个条件时等价于
db.survey.find(
    { "results.score": 8}
)
//多个条件
db.survey.find(
   { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)

3. 对象数组的Upsert

mongo没有提供对象数组的Upsert操作——不存在时插入,存在时更新。实现方法就是
a. 当不知道是否存在时使用$addToSet。如果已经存在,则什么都不发生
如果插入的是多个元素,需要使用$each,否则将以整个输入添加

>db.stores.update(
    {"_id":1},
    {$addToSet:{$each:{"fruits":["apple", "oranges"]}}}
)

b. 确定存在时,使用Update
下面是mongodb的官方解释:

$addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.

update时需要使用$运算符

db.survey.update(
    { "results": { $elemMatch : { "score" : {$eq : 8}}},{$set:{"results.$.product":"cba"}}}
)

4. 从数组删除对象

使用$pull

{
   _id: 1,
   fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
   vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
   _id: 2,
   fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
   vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}
//删除apples,oranges
db.stores.update(
    { },
    { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
    { multi: true }
)
//当然可以使用$eq, $ne,$gt等等条件判断删除元素

注意不能使用$elemMatch进行对象数组的删除

Because $pull operator applies its query to each element as though it were a top-level object, the expression did not require the use of $elemMatch to specify the condition of a score field equal to 8 and item field equal to “B”. In fact, the following operation will not pull any element from the original collection.

你可能感兴趣的:(MongoDB)