简体   繁体   English

匹配mongodb php的元素

[英]elements matching mongodb php

my question is how I can translate into php the following js code from mongodb : 我的问题是我如何将mongodb中的以下js代码转换为php:

t.find( { group:3, 'x.a':2 }, { 'x.$':1 } ).toArray()[0].x.length, "single object match (array length match)" ); t.find({group:3,'x.a':2},{'x。$':1}).toArray()[0] .x.length,“单个对象匹配(数组长度匹配)” );

You can find the whole js code at : 您可以在以下位置找到整个js代码:

https://github.com/mongodb/mongo/blob/83ec59844bdd629b2b32a9791a4e7a0e93516c02/jstests/elemMatchProjection.js https://github.com/mongodb/mongo/blob/83ec59844bdd629b2b32a9791a4e7a0e93516c02/jstests/elemMatchProjection.js

Basically what I care about is how can I translate into php toArray()[0].x.length ? 基本上,我关心的是如何将PHP转换为toArray()[0] .x.length? I know php has count but I don't care about that. 我知道php有计数,但我不在乎。 I have other advanced queries and all of them reduce to this question. 我还有其他高级查询,所有这些都简化为这个问题。

The literal translation of toArray()[0].x.length would be: toArray()[0].x.length的字面翻译为:

$cursor = $collection->find(['group' => 3, 'x.a' => 2], ['x.$' => 1]);
$documents = iterator_to_array($cursor, false);
count($documents[0]['x']);

Alternatively, it would be easier to use MongoCollection::findOne() in the above example, since we're only working with the first result and ignoring any others. 另外,在上面的示例中,使用MongoCollection :: findOne()会更容易,因为我们只处理第一个结果,而忽略其他任何结果。 Rewritten: 改写:

$document = $collection->findOne(['group' => 3, 'x.a' => 2], ['x.$' => 1]);
count($document['x']);

I didn't follow what you mean by "I know php has count but I don't care about that." 我没有遵循您的意思:“我知道php很有用,但我不在乎。” Unless you were referring to MongoCollection::count() , the basic count() is necessary to calculate the length of the array in the returned document. 除非您引用MongoCollection :: count() ,否则基本count()是计算返回文档中数组长度的必要条件。

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

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