简体   繁体   English

MongoDB-将带有_id的文档嵌入到子级中

[英]MongoDB - Embed document with _id into the child

I have a document that represents a store with your advertisements as follows: 我有一个代表您的广告的商店的文档,如下所示:

{name: "name of store",
 address: "address of store",
 advertisements: [{title: "title of advertising", desc: "desc of advertising"}]
}

To increase read speed and insert or find an advertising from this store is easy but, to delete a specific advertising, how can I do this? 要提高阅读速度并在此商店中插入或查找广告很容易,但是要删除特定广告,我该怎么做?

There is a way to add a _id field into the element inside advertisements array? 有没有一种方法可以在广告数组内的元素中添加_id字段? This way, I could find a specific item by _id. 这样,我可以通过_id找到特定的项目。

I don't like the approach that use $elemMatch to find an item by your name or other field that isn't de _id. 我不喜欢使用$ elemMatch通过您的姓名或其他不是_id的字段来查找项目的方法。

Thanks! 谢谢!

With embedded documents there are no _id fields, these are a property of the main document in the collection. 对于嵌入式文档,没有_id字段,这是集合中主文档的属性。 There is a full explaination here: http://docs.mongodb.org/manual/core/document/ 这里有完整的解释: http : //docs.mongodb.org/manual/core/document/

Any embedded documents or array elements or even documents within arrays are stored exactly as is, an in the natural form of how you would work with JSON structures or very close to most dynaminc language native representations. 任何嵌入的文档或数组元素,甚至数组中的文档都按原样存储,这是使用JSON结构或非常接近大多数动态语言本机表示形式的自然形式。

In your case for documents within an array you can either use the $elemMatch query operator to find the document(s) you wish to remove. 对于数组中的文档,可以使用$ elemMatch查询运算符查找要删除的文档。

{ name: "<matching name>", advertisements: { $elemMatch: { title: 'title of advertising'  } } }

Alternately there is the dot notation approach: 也可以使用点表示法:

{ name: "<matching name>", advertisements.title = 'title of advertising' }

Or even index notation: 甚至索引符号:

{ name: "<matching name>", advertisements[0] }

At any rate there are a collection of Array operators for use in updates so you can manipulate the elements. 无论如何,都有用于更新的Array运算符集合,因此您可以操纵元素。

Perhaps your real problem here is not with $elemMatch but with the structure of the documents contained having no unique key in which to access them. 也许您真正的问题不是$ elemMatch,而是包含的文档结构没有访问它们的唯一密钥 That being the case then maybe you should consider altering the structure of the sub-documents in your data to have a reasonable identifier for use in finding the documents you want. 在这种情况下,也许您应该考虑更改数据中子文档的结构,以具有合理的标识符以用于查找所需的文档。 This is generally a best practice approach. 通常,这是最佳做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM