Mongo数组更新或推入一个查询

时间:2017-04-06 16:00:36

标签: arrays mongodb

假设我们有包含以下形状文档的mongo集合:

-(void)createSomeLabel {
    // Create and position my label
    UILabel *someLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,
                                                                   0,
                                                                   self.view.frame.size.width - 40.0,
                                                                   self.view.frame.size.height - 300.0)];
    someLabel.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
    someLabel.textAlignment = NSTextAlignmentCenter;
    someLabel.textColor = [UIColor whiteColor];
    someLabel.lineBreakMode = NSLineBreakByWordWrapping;
    someLabel.numberOfLines = 0;
    [self.view addSubview:someLabel];

    // This string will be different lengths all the time
    NSString *someLongString = @"Here is a really long amount of text that is going to wordwrap/line break and I don't want to highlight the spacing. I want to just highlight the words and a single space before/after the word";

    // Create attributed string
    NSMutableAttributedString *someLongStringAttr = [[NSMutableAttributedString alloc] initWithString:someLongString attributes:nil];

    // Apply background color
    [someLongStringAttr addAttribute:NSBackgroundColorAttributeName
                               value:[UIColor colorWithWhite:0 alpha:0.25]
                               range:NSMakeRange(0, someLongStringAttr.length)];

    // Set text of label
    someLabel.attributedText = someLongStringAttr;
}

但有时 { _id: '1234', letters: ['a', 'b', 'c', 'd'], } 字段可能是letters

我想知道是否可以在单个查询中实现以下功能

  • 如果null数组非空,请将第一项设置为“x”。
  • 否则,请将letters字段设置为letters

当然,最简单的想法不起作用

['x']

因为如果尚未设置db.collection.update({_id: '...'}, {$set:{'letters.0':'x'}}); 字段,则上述操作的结果将为:

letters

有没有办法告诉mongo我的意图是创建一个数组,而不是一个对象?

2 个答案:

答案 0 :(得分:2)

如果您关心阵列上的重复项,可以使用$push运算符或$addToSet

您的查询将如下所示:

set samples 1000

答案 1 :(得分:0)

如果要更新数组中的第一个

弹出旧的第一个

db.collection.update({_id:xx}, {$pop:{letters : -1}})

然后推到第一个

db.collection.update({_id:xx}, {$push:{letters : {$each:['first one'], $position:0}}})