从Mongo中的集合中提取值

时间:2016-01-04 05:00:02

标签: mongodb mongodb-query

如何从Mongo中的集合中提取值?

这是我试过用来拉取其中一个集合中的一个值的查询。

我正在尝试删除集合srs.5689f5206f404774fc350407

中数组中的值



db.dbName.update(
{ _id: ObjectId("5689e240d3235cbef83e41d0") },
{ $pull:{ 'srs.5689f5206f404774fc350407.$.flashcardID':
          ObjectId("5689f52e6f404774fc35040a")}
})




这是有问题的文件。



{
   "_id":ObjectId("5689e240d3235cbef83e41d0"),
   "username":"lol1",
   "score":"",
   "decks":[
      "5689e246d3235cbef83e41d1"
   ],
   "srs":{
      "5689e246d3235cbef83e41d1":[
         {
            "timer":1451876940132,
            "flashcardID":ObjectId("5689e24cd3235cbef83e41d2"),
            "correct":0,
            "type":"srs"
         },
         {
            "timer":1451876944421,
            "flashcardID":ObjectId("5689e250d3235cbef83e41d3"),
            "correct":0,
            "type":"srs"
         },
         {
            "timer":1451876949586,
            "flashcardID":ObjectId("5689e255d3235cbef83e41d4"),
            "correct":0,
            "type":"srs"
         },
         {
            "timer":1451876954478,
            "flashcardID":ObjectId("5689e25ad3235cbef83e41d5"),
            "correct":0,
            "type":"srs"
         },
         {
            "timer":1451876957760,
            "flashcardID":ObjectId("5689e25dd3235cbef83e41d6"),
            "correct":0,
            "type":"srs"
         }
      ]
   },
   "type":"user"
}






WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 16837,
                "errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: srs.5689f5206f404774fc350407.$.flashcardID"
        }
})




我想知道该怎么做。我已经尝试修复此查询已有一段时间了。

2 个答案:

答案 0 :(得分:3)

db.dbName.update({
        _id: "5689e240d3235cbef83e41d0"
}, {
    $pull: {
        "srs.5689e246d3235cbef83e41d1": {
            "flashcardID": "5689e24cd3235cbef83e41d2"
        }
    }
})

试试这个。在这种情况下,“$ pull”在“srs.5689e246d3235cbef83e41d1”之后你需要告诉你要拉的是第一个键,然后在where子句找到你的值“”flashcardID“:”5689e24cd3235cbef83e41d2“”。阅读文档 https://docs.mongodb.org/manual/reference/operator/update/pull/

答案 1 :(得分:1)

  1. 架构似乎没有使用objectid - 而是一个字符串。除非印刷得很好......

  2. $不是运营商。你可能会想到$in运算符。在这种情况下,似乎不需要只使用闪卡字符串。

    db.dbName.update( {_id:“5689e240d3235cbef83e41d0”}, {$ pull:{“srs.5689f5206f404774fc350407”:{“flashcardID”:“5689f52e6f404774fc35040a”}}} )