如何在MongoDB中存储具有以$开头的密钥的对象 [英] How to store an object in MongoDB that has a key that starts with $

查看:252
本文介绍了如何在MongoDB中存储具有以$开头的密钥的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想保存对文档所做的更改.最简单的方法是存储对文档所做的实际更改.我的意思是:

I want to save changes made to my document. The easiest way to do this is to store the actual changes made to a document. What I mean:

var changes = {
  $set: {
    text: 'Some text.'
  }
}

db.posts.update({
  _id: _id
}, changes)

db.changes.insert({
  postid: _id,
  changes: changes
})

但是我遇到错误了(有充分的理由):

However I'm getting the error (with good reason):

Error: key $set must not start with '$'

存储更改的最简单方法是什么?

What's the easiest way to store changes?

或者我正在错误地解决问题,并且您有更好的解决方案.我希望用户能够看到人们对任何帖子或实际上任何内容所做的更改的日志.我不会在每次更改时都发挥作用.编辑文本只是对文档进行更改的多种方法之一.

Or perhaps I'm approaching the problem wrong and you have a better solution. I want users to be able to see a log of changes people make to any post or, in fact, anything. I'm not going to make a function for every time of change. Editing the text is just one of many ways to make changes to a document.

推荐答案

这是MongoDB中的限制.由于查询的工作方式,某些保留字符之一为$.使用运算符时,集合中的文档和用于更新的文档之间会存在歧义.

This is a limitation within MongoDB. There are certain reserved characters one of them being $ due to how querying must work. When using operators there would be ambiguity between the document in the collection and the document used for updating.

我建议去除$符号.我会改用这些词代替您尝试使用的运算符:

I would recommend stripping out the $ symbols. I would instead use these words in place of the operators you are trying to use:

  • 创建
  • 设置
  • 删除

这篇关于如何在MongoDB中存储具有以$开头的密钥的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆