Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

mongodb - Referencing Other Documents by String rather than ObjectId

Let's say I have two collections:

Products and Categories.

The latter collection's documents have 2 fields:

  • _id (BSON ObjectId)
  • Name (String)

The latter collection's documents have 3 fields:

  • _id (BSON ObjectId)
  • Name (String)
  • Products (Array of Strings)

Assume I have the following Product document:

{ "_id" : ObjectId("AAA"), "name" : "Shovel" }

Let's say I have the following Category document:

{ "_id" : ObjectId("BBB"), "Name" : "Gardening", "Products" : ["AAA"] }

For purposes of this example, assume that AAA and BBB are legitimate ObjectId's - example: ObjectId("523c7df5c30cc960b235ddee") where they would equal the inner ObjectId's string.

Should the Products field be stored as ObjectId(...)'s rather than as Strings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't think it really matters that much.

I'm pretty sure that the ObjectId format encodes a hex number, so it is probably slightly more efficient with memory and bandwidth. I have done it both ways. As long as you decide, for each field, how you are going to encode it, either will work just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...