我有一个包含以下集合的数据库:
{id1: "1", id2: "a"}, {id1: "2", id2: "a"}, {id1: "3", id2: "a"}, {id1: "1", id2: "b"}, {id1: "2", id2: "b"}
我希望在id2
:1,2
id1
给出的答案应为b
,因为它是唯一只有id2
的{{1}}
如果给出的'id1'列表是:1,2,3那么'id2'应该是'a',因为'a'与1,2 AND 3相关
如何在 Mongodb 上查询,最好使用聚合。
答案 0 :(得分:0)
我想我明白你要做的事情。您可以使用汇总查询来完成,但它不是非常直接的:
public class MainActivity extends AppCompatActivity {
ListView myListView;
Cursor myCursor;
String[] proj;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DbUtil dbUtil=new DbUtil(getApplicationContext());
dbUtil.open();
dbUtil.insertRandomNames();
myCursor=dbUtil.fetchAllData(); //getting my ordered cursor
myListView=(ListView)findViewById(R.id.list);
myListView.setFastScrollEnabled(true); //must be enabled
myListView.setAdapter(
new MyCursorAdapter(
getApplicationContext(),
android.R.layout.simple_list_item_1,
myCursor,
new String[]{DbUtil.KEY_NAME},//from
new int[]{android.R.id.text1}) //to
);
dbUtil.close();
}
class MyCursorAdapter extends SimpleCursorAdapter implements SectionIndexer{
AlphabetIndexer alphaIndexer;
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
alphaIndexer=new AlphabetIndexer(c, myCursor.getColumnIndex(DbUtil.KEY_NAME), " ABCDEFGHIJKLMNOPQRSTUVWXYZ");
// you have just to instanciate the indexer class like this
//cursor,index of the sorted colum,a string representing the alphabeth (pay attention on the blank char at the beginning of the sequence)
}
@Override
public int getPositionForSection(int section) {
return alphaIndexer.getPositionForSection(section); //use the indexer
}
@Override
public int getSectionForPosition(int position) {
return alphaIndexer.getSectionForPosition(position); //use the indexer
}
@Override
public Object[] getSections() {
return alphaIndexer.getSections(); //use the indexer
}
}
}
此查询将按id2对文档进行分组,并创建一个包含id1值的集合。然后它匹配组中的文档,查看id1Set的大小(应该是2),id1Set中的值应该包含所有" 1"和" 2"。
由于您的示例数据包含id2的字符串值(" 1"和" 2"而不是1和2),因此匹配是字符串值而不是数字。