【问题标题】:Pulling from a value from a collection in Mongo从 Mongo 的集合中提取值
【发布时间】:2016-01-04 13:32:33
【问题描述】:

如何从 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"
        }
})

我想要一些关于该怎么做的建议。我已经尝试修复此查询很长一段时间了。

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:
    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/

    【讨论】:

    • 谢谢我现在明白了。
    【解决方案2】:
    1. 看来架构没有使用objectid——而是一个字符串。除非印得很漂亮……

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

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

    【讨论】:

    • 我使用的是 json 格式化程序,所以我无法拥有 ObjectId。在真实模式中,它确实包含 ObjectId。该查询匹配了一个文档,但没有修改它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多