0

我有这样的文件:

{ _id:ObjectID, list:Array }

该列表包含表单的元素(我将其称为 listElement):

{ _id:ObjectID, time:Number }

我想更新 2 个特定 listElements 的时间子字段,每个子字段都有自己不同的值。我可以访问 listElements 的两个 _id。

关于这个问题的相关事情:将列表从数组转换为键是 _id 值的对象会更好吗?所以我会做 db.update( ( _id:"Document id" }, { "list.423rfasf2q3.time":200, "list.fjsdhfksjdh2432.time":100 } ) ?

我不确定如何使用 ObjectID 作为键,但我想我可以将它串起来,并且 _id 值和包含该 listElement 的键都是相同的字符串。

4

1 回答 1

2

You can't update two docs with two different values, you'll need to run it as two separate updates.

You do not want to put data into your key values, it's better to leave them as they are. There's no good way to match key values outside of $exists and even that does not support wildcards. So you'd have to get the ObjectId, convert it to a string, concatenate it into the key, then query for documents where that key exists. It's much easier to just put the value in a document in an array. Additionally, there's no way to index key values in MongoDB, so if you want to index your data you'll need to have it in the array as a data element.

Edit to include positional match example

First, insert two documents

> db.test.insert( {list: [ {_id: new ObjectId(), time: 1234}, {_id: new ObjectId(), time: 4556} ] } )
>

Demonstrate that they are both there

> db.test.find()
{ "_id" : ObjectId("5215036749177daf439a2ffe"), "list" : [{ "_id" : ObjectId("5215036749177daf439a2ffc"), "time" : 1234 }, { "_id" :
ObjectId("5215036749177daf439a2ffd"), "time" : 4556 } ] }
>

Show that if we do a normal array filter we get all elements of the array

> db.test.find({"list._id":ObjectId("5215036749177daf439a2ffc")})
{ "_id" : ObjectId("5215036749177daf439a2ffe"), "list" : [ { "_id" : ObjectId("5215036749177daf439a2ffc"), "time" : 1234 }, { "_id" :
ObjectId("5215036749177daf439a2ffd"), "time" : 4556 } ] }
>

Demonstrate that we can use the $ operator to only return the first array element that was matched

> db.test.find({"list._id":ObjectId("5215036749177daf439a2ffc")}, {_id: 0, "list.$": 1})
{ "list" : [ { "_id" : ObjectId("5215036749177daf439a2ffc"), "time" : 1234 } ] }
于 2013-08-21T13:55:42.380 回答