如何在 mongodb shell 查询中使用 guid
使用 MongoDB shell 时,如何使用 guid 数据类型(我已将其用作集合中的 _id)。
以下格式无效:
>db.person.find({"_id","E3E45566-AFE4-A564-7876-AEFF6745FF"});
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以轻松使用:
You can use easily:
您必须将 _id 值与 BinData 实例进行比较(而不是与字符串进行比较)。不幸的是 BinData 构造函数采用 Base64 字符串而不是十六进制字符串。
您的 GUID 值末尾缺少两个十六进制数字,因此出于本示例的目的,我将假设它们为“00”。以下值是等效的:
所以您的查询应该是:
我假设二进制子类型已正确设置为 3。如果没有,则使用了什么驱动程序创建数据?
You have to compare the _id value against an instance of BinData (not against a string). Unfortunately the BinData constructor takes a Base64 string instead of a hex string.
Your GUID value is missing two hex digits at the end, so for the purposes of this example I will assume they are "00". The following values are equivalent:
So your query should be:
I am assuming that the binary subtype was correctly set to 3. If not, what driver was used to create the data?
您可以在查询前面使用以下 js 函数,如下所示:
您可以将函数保存在 .js 文件中并加载它或在进行查询之前打开它,如果您从结果中复制值,则应将函数重命名为:
You could use the following js function in front of your query like so:
You could save the function in .js file and load it or open it before you make your query and if you copy the value from your results you should rename the function with:
我知道这是一个老问题,但如果没有任何额外的需求,您可以使用这个:
I know it's an old issue, but without any additional needs you can use this one:
老问题的新答案,但该线程中的代码示例都不适合我。
看起来 BinData 类型 03 有多个子类型,具体取决于语言。检查 mongo-java-driver 代码 此处。
对于Java,UUID被分成两半,然后每一半被翻转。
此 python 代码可以将 UUID 转换为 BinData() 类型 03 子类型 JAVA_LEGACY 并返回 UUID:
:
所示
查询的结果如下
New answer to an old question, but none of the code examples in this thread worked for me.
It looks like BinData type 03 has multiple subtypes, depending on the language. Check the mongo-java-driver code here.
For Java, the UUID is split into two halves and then each half is flipped.
This python code can translate UUIDs to BinData() type 03 subtype JAVA_LEGACY and back to UUID:
The result of
is
The query then looks like:
您可以使用 split() 和 join() 解决方法来解决此问题:
例如,如果我使用 "E3E45566-AFE4-A564-7876-AEFF6745FF" 十六进制值和
-
在UUID()
函数内部,它不会在 mongo 中返回BinData
,因此请尝试在传递给UUID-
代码>函数。或者通过定义一个变量来在多行中执行此操作:
或者通过创建一个简单的函数:
You can fix this issue by using split() and join() workaround:
for instance if I use "E3E45566-AFE4-A564-7876-AEFF6745FF" hex value with
-
insideUUID()
function, it does not returnBinData
in mongo so please try removing all the-
before passing toUUID
function.Or by defining a variable to do it in multiple line:
or by creating a simple function: